package com.coffee.order.service.sku.impl;

import com.coffee.sku.api.sku.query.SkuSalesInformationQuery;
import com.google.common.collect.Lists;

import com.coffee.admin.api.common.service.SmsCodeService;
import com.coffee.admin.api.merchant.result.MerchantResult;
import com.coffee.admin.api.merchant.service.MerchantService;
import com.coffee.admin.api.supplier.query.SupplierQuery;
import com.coffee.admin.service.common.bean.AdminMenu;
import com.coffee.daili.api.service.DailiMerchantService;
import com.coffee.order.api.sku.req.*;
import com.coffee.order.api.sku.result.SkuOrderResult;

import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.common.query.GtRegionQuery;
import com.coffee.admin.api.merchant.query.MerchantQuery;
import com.coffee.admin.api.platform.query.PlatformSystemDeployQuery;
import com.coffee.admin.service.common.bean.GtRegion;
import com.coffee.admin.service.common.dao.GtRegionDao;
import com.coffee.admin.service.merchant.bean.Merchant;
import com.coffee.admin.service.merchant.bean.MerchantCity;
import com.coffee.admin.service.merchant.bean.MerchantIntegralLog;
import com.coffee.admin.service.merchant.dao.MerchantCityDao;
import com.coffee.admin.service.merchant.dao.MerchantDao;
import com.coffee.admin.service.merchant.dao.MerchantIntegralLogDao;
import com.coffee.admin.service.platform.bean.Platform;
import com.coffee.admin.service.platform.bean.PlatformSystemDeploy;
import com.coffee.admin.service.platform.dao.PlatformDao;
import com.coffee.admin.service.platform.dao.PlatformSystemDeployDao;
import com.coffee.admin.service.supplier.bean.Supplier;
import com.coffee.admin.service.supplier.dao.SupplierDao;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.*;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.util.*;
import com.coffee.daili.api.query.DailiMerchantQuery;
import com.coffee.daili.api.query.DailiMerchantSkuQuery;
import com.coffee.daili.api.query.DailiOrderQuery;
import com.coffee.daili.service.bean.DailiMerchant;
import com.coffee.daili.service.bean.DailiMerchantSku;
import com.coffee.daili.service.bean.DailiOrder;
import com.coffee.daili.service.dao.DailiMerchantDao;
import com.coffee.daili.service.dao.DailiMerchantSkuDao;
import com.coffee.daili.service.dao.DailiOrderDao;
import com.coffee.order.api.inquire.result.WeiXinPushResult;
import com.coffee.order.api.sku.query.*;
import com.coffee.order.api.sku.result.*;
import com.coffee.order.api.sku.service.SkuOrderService;
import com.coffee.order.service.inquire.bean.InquireOrderPlan;
import com.coffee.order.service.sku.bean.*;
import com.coffee.order.service.sku.dao.*;
import com.coffee.sku.api.sku.query.RegionalSkuSalesInformationQuery;
import com.coffee.sku.api.sku.query.SkuQuery;
import com.coffee.sku.api.sku.result.SkuContentResult;
import com.coffee.sku.service.sku.bean.*;
import com.coffee.sku.service.sku.dao.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@DubboService(dynamic = true)
public class SkuOrderServiceImpl implements SkuOrderService {
    private final static Logger logger = LoggerFactory.getLogger(SkuOrderServiceImpl.class);
    @Value("${cityId}")
    private String nationwideId;
    @Autowired
    private SkuOrderDao skuOrderDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private MerchantCityDao merchantCityDao;
    @Autowired
    private GtRegionDao gtRegionDao;
    @Autowired
    private SkuDao skuDao;
    @Autowired
    private PayOrderDao payOrderDao;
    @Autowired
    private SkuContentDao skuContentDao;
    @Autowired
    private PeriodizationSkuDao periodizationSkuDao;
    @Autowired
    private SkuCategoryDao skuCategoryDao;
    @Autowired
    private SkuSalesInformationDao skuSalesInformationDao;
    @Autowired
    private MerchantDao merchantDao;
    @Autowired
    private MerchantIntegralLogDao merchantIntegralLogDao;
    @Autowired
    private PlatformSystemDeployDao platformSystemDeployDao;
    @Autowired
    private SkuOrderDetailDao skuOrderDetailDao;
    @Autowired
    private SkuOrderDetailPeriodizationDao skuOrderDetailPeriodizationDao;
    @Autowired
    private SkuOrderDeliveryDemandDao skuOrderDeliveryDemandDao;
    @Autowired
    private PlatformDao platformDao;
    @Autowired
    private SupplierDao supplierDao;
    @Autowired
    private SkuShopcarDao skuShopcarDao;
    @Autowired
    private DailiMerchantDao dailiMerchantDao;
    @Autowired
    private DailiMerchantSkuDao dailiMerchantSkuDao;
    @Autowired
    private DailiOrderDao dailiOrderDao;
    @Autowired
    private EnjoyBeforePaySkuDao enjoyBeforePaySkuDao;
    @Autowired
    private RegionalSkuSalesInformationDao regionalSkuSalesInformationDao;
    @Autowired
    private RegionalSkuDao regionalSkuDao;
    @Autowired
    private UrbanFullReductionDao urbanFullReductionDao;
    @Autowired
    private OrderBalanceDao orderBalanceDao;
    @DubboReference
    private SmsCodeService smsCodeService;

    @Value("${TAG}")
    private String environment;
    @Value("${enjouyDay}")
    private String enjouyDay;
    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Override
    public Page<SkuOrderResult> getPager(SkuOrderQuery param, PagerInfo pr) {
        Page<SkuOrderResult> pager = new Page<SkuOrderResult>(pr.getStart(), pr.getPageSize());
        Integer count = skuOrderDao.count(param);
        pager.setTotalPage(count);
        if (count > 0) {
            List<SkuOrder> list = skuOrderDao.page(param, pr.getStart(), pr.getPageSize());
            pager.setData(DTOUtils.convertList(list, SkuOrderResult.class));
        }
        return pager;
    }

    @Override
    public Integer count(SkuOrderQuery param) {
        Integer count = skuOrderDao.count(param);
        return count;
    }


    @Override
    public List<MerchantSpellOrderResult> skuOrderService(Integer skuId, Integer spellOrderPeople) {
        List<MerchantSpellOrderResult> merchantSpellOrderResults = new ArrayList<>();
        SkuOrderQuery param = new SkuOrderQuery();
        param.setSkuId(skuId);
        param.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
        param.setType(SkuTypeEnum.PART.getCode());
        param.setPartStatus(SkuOrderStatusEnum.WAITING.getCode());
        param.setPartFinshTime(new Date());
        param.setIsApply("N");
        param.setIsSponsor("Y");
        List<SkuOrder> list = skuOrderDao.list(param);
        if (list != null && list.size() > 0) {
            merchantSpellOrderResults = DTOUtils.convertList(list, MerchantSpellOrderResult.class);
            for (MerchantSpellOrderResult merchantSpellOrderResult : merchantSpellOrderResults) {
                Merchant merchant = merchantDao.findById(merchantSpellOrderResult.getMerchantId());
                merchantSpellOrderResult.setName(merchant.getName());
                SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
                skuOrderQuery.setPartSn(merchantSpellOrderResult.getPartSn());
                skuOrderQuery.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
                Integer count = skuOrderDao.count(skuOrderQuery);
                merchantSpellOrderResult.setFewPeople(spellOrderPeople - count);
            }
        }

        return merchantSpellOrderResults;
    }


    @Override
    public List<SkuOrderResult> getList(SkuOrderQuery param, PagerInfo pr) {
        List<SkuOrder> list = skuOrderDao.page(param, pr.getStart(), pr.getPageSize());
        return DTOUtils.convertList(list, SkuOrderResult.class);
    }

    @Override
    public List<SkuOrderResult> getList(SkuOrderQuery param) {
        List<SkuOrder> list = skuOrderDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, SkuOrderResult.class);
    }

    @Override
    public List<SkuOrderResult> getList() {
        SkuOrderQuery param = new SkuOrderQuery();
        List<SkuOrder> list = skuOrderDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, SkuOrderResult.class);
    }


    @Override
    public void delete(Integer id) {
        skuOrderDao.deleteById(id);
    }


    @Override
    public Map<Integer, SkuOrderResult> getItemMap(Set<Integer> idSet) {
        Map<Integer, SkuOrderResult> map = new HashMap<Integer, SkuOrderResult>();
        List<SkuOrder> list = skuOrderDao.findByIds(StringUtil.setToList(idSet));
        List<SkuOrderResult> resultList = DTOUtils.convertList(list, SkuOrderResult.class);
        for (SkuOrderResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    public RegionalSkuSalesInformation getRegionalSkuSalesInformation(Integer chooseCityId, Integer cityId, Integer skuSalesInformationId, String title) throws BusinessException {
        if (cityId == null) {
            return null;
        }
        RegionalSkuSalesInformationQuery regionalSkuSalesInformationQuery = new RegionalSkuSalesInformationQuery();
        regionalSkuSalesInformationQuery.setGtRegionId(cityId);
        regionalSkuSalesInformationQuery.setSkuSalesInformationId(skuSalesInformationId);
        RegionalSkuSalesInformation regionalSkuSalesInformation = regionalSkuSalesInformationDao.findFirst(regionalSkuSalesInformationQuery);
        if (regionalSkuSalesInformation != null && chooseCityId != null) {
            if (!cityId.equals(chooseCityId)) {
                GtRegion gtRegion = gtRegionDao.findById(cityId);
                throw new BusinessException(ExceptionEnum.ERROR_1710.getCode(), ExceptionEnum.ERROR_1710.getMessage().replace("XX", gtRegion.getName()));
            }
        }
        return regionalSkuSalesInformation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderResult addOrderByDirect(SkuOrderAddByDirectReq req) throws BusinessException {
        Merchant merchant = merchantDao.findById(req.getMerchantId());
        if ("Y".equals(req.getIsByBalance())&&merchant.getBalance()<0.0){
            throw new BusinessException(ExceptionEnum.ERROR_1714.getCode(), ExceptionEnum.ERROR_1714.getMessage());
        }
        OrderResult orderResult = new OrderResult();
        List<String> skuNames = new ArrayList<>();
        Sku sku = skuDao.findById(req.getSkuId());
        ValidateBusinessException.assertNonNull(sku, ExceptionEnum.ERROR_1701);
        ValidateBusinessException.assertFalse("N".equals(sku.getIsEnable()), ExceptionEnum.ERROR_1702);
        skuNames.add(sku.getTitle());
        orderResult.setSkuNames(skuNames);
        SkuContent skuContent = skuContentDao.findBySkuId(req.getSkuId());
        ValidateBusinessException.assertNonNull(skuContent, ExceptionEnum.ERROR_1701);
        ValidateBusinessException.assertFalse("Y".equals(req.getIsSpellOrder()) && !"Y".equals(skuContent.getIsSpellOrder()), ExceptionEnum.ERROR_1856);
        SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(req.getSkuSalesInformationId());
        ValidateBusinessException.assertNonNull(skuSalesInformation, ExceptionEnum.ERROR_1703);
        ValidateBusinessException.assertFalse(skuSalesInformation.getStock() < req.getCount(), sku.getTitle() + (ExceptionEnum.ERROR_1816.getMessage()));
        MerchantCity merchantCity = getMerchantCity(req.getMerchantCityId());
        if (req.getCityId() != null) {
            RegionalSku regionalSku = regionalSkuDao.findBySkuId(req.getSkuId());
            if (regionalSku != null) {
                if ("N".equals(req.getIsByBalance()) && "Y".equals(regionalSku.getIsMembersExclusive())) {
                    throw new BusinessException(ExceptionEnum.ERROR_1713.getCode(), sku.getTitle() + "," + ExceptionEnum.ERROR_1713.getMessage());
                }
            }
        }
        RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(merchantCity.getCityId(), req.getCityId(), req.getSkuSalesInformationId(), sku.getTitle());
        //判断是否参与和拼团人数够
        if (StringUtils.isNotEmpty(req.getPartSn())) {
            SkuOrderQuery param = new SkuOrderQuery();
            param.setPartSn(req.getPartSn());
            param.setMerchantId(req.getMerchantId());
            param.setNoStatus(SkuOrderStatusEnum.CANCEL.getCode());
            SkuOrder first = skuOrderDao.findFirst(param);
            ValidateBusinessException.assertNull(first, ExceptionEnum.ERROR_1860);
            param = new SkuOrderQuery();
            param.setPartSn(req.getPartSn());
            param.setIsApply("N");
            param.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
            List<SkuOrder> list = skuOrderDao.list(param);
            if (list == null || list.size() <= 0) {
                throw new BusinessException(ExceptionEnum.ERROR_1851.getCode(), ExceptionEnum.ERROR_1851.getMessage());
            }
            if (list.size() >= skuContent.getSpellOrderPeople()) {
                throw new BusinessException(ExceptionEnum.ERROR_1852.getCode(), ExceptionEnum.ERROR_1852.getMessage());
            }
            param = new SkuOrderQuery();
            param.setPartSn(req.getPartSn());
            param.setIsApply("Y");
            SkuOrder skuOrder = skuOrderDao.findFirst(param);
            if (skuOrder.getPartFinshTime().before(new Date())) {
                throw new BusinessException(ExceptionEnum.ERROR_1859.getCode(), ExceptionEnum.ERROR_1859.getMessage());
            }
        }

        Order order = new Order();
        order.setMerchantId(req.getMerchantId());
        order.setOrderType(SkuTypeEnum.SKU.getCode());
        order.setCreateTime(new Date());
        order.setMerchantCityId(req.getMerchantCityId());
        order.setReceiver(merchantCity.getReceiver());
        order.setReceiverMobile(merchantCity.getReceiverMobile());
        order.setSupplierId(sku.getSupplierId());
        order.setAddress(merchantCity.getProvinceName() + merchantCity.getCityName() + merchantCity.getAreaName() + merchantCity.getAddress());
        orderDao.insert(order);

        //支付价格
        String isRegion = "N";
        Double unitPrice = skuSalesInformation.getPrice();
        SkuOrder skuOrder = new SkuOrder();
        skuOrder.setType(SkuTypeEnum.SKU.getCode());
        Integer count = req.getCount();
        //总价
        double price = skuSalesInformation.getPrice() * count;
        if (regionalSkuSalesInformation != null) {
            price = regionalSkuSalesInformation.getRegionalPrice() * count;
            unitPrice = regionalSkuSalesInformation.getRegionalPrice();
            isRegion = "Y";
        }
        if ("Y".equals(req.getIsSpellOrder())) {
            price = skuSalesInformation.getSpellOrderPrice() * count;
        }
        //积分价格
        Double integralPrice = 0.0;
        //积分
        Integer integral = 0;

        Double freight = 0.0;
        //计算积分抵扣金额
        if ("Y".equals(skuContent.getIsIntegral()) && "Y".equals(req.getIsUseIntegral())) {
            IntegerPrice integerPrice = getIntegral(req.getIsUseIntegral(), price, merchant, skuContent, skuSalesInformation, regionalSkuSalesInformation);
            integralPrice = integerPrice.getIntegralPrice();
            integral = integerPrice.getIntegral();
            skuOrder.setType(SkuTypeEnum.INTEGRAL.getCode());
        }
        Double payPrice = new BigDecimal(price).subtract(new BigDecimal(integralPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
        payPrice = payPrice > 0 ? payPrice : 0;
        skuOrder.setMerchantId(req.getMerchantId());
        skuOrder.setOrderId(order.getId());
        skuOrder.setTotalPrice(price);
        skuOrder.setPayPrice(payPrice);
        skuOrder.setIntegralPrice(integralPrice);
        skuOrder.setIntegral(integral);
        skuOrder.setStatus(SkuOrderStatusEnum.WAITING.getCode());
        skuOrder.setSupplierId(sku.getSupplierId());
        skuOrder.setBuyWay(SkuOrderBuyTypeEnum.DIRECT.getCode());
        skuOrder.setOrderType("Y".equals(req.getIsByBalance()) ? SkuOrderTypeEnum.BALANCE.getCode() : SkuOrderTypeEnum.BUY.getCode());
        skuOrder.setIsRegion(isRegion);
        //拼团商品操作
        if ("Y".equals(req.getIsSpellOrder()) && "Y".equals(skuContent.getIsSpellOrder())) {
            if (!merchantCity.getProvinceId().equals(skuContent.getSpellOrderProvinceId()) || !merchantCity.getCityId().equals(skuContent.getSpellOrderCityId())) {
                throw new BusinessException(ExceptionEnum.ERROR_1857.getCode(), ExceptionEnum.ERROR_1857.getMessage());
            }
            PlatformSystemDeployQuery secondPlatformSystemDeployQuery = new PlatformSystemDeployQuery();
            secondPlatformSystemDeployQuery.setType(SkuTypeEnum.PART.getCode());
            secondPlatformSystemDeployQuery.setStatus("finishTime");
            PlatformSystemDeploy secondPlatformSystemDeploy = platformSystemDeployDao.findFirst(secondPlatformSystemDeployQuery);
            ValidateBusinessException.assertNonNull(secondPlatformSystemDeploy, ExceptionEnum.ERROR_1705);
            skuOrder.setType(SkuTypeEnum.PART.getCode());
            if (StringUtils.isNotEmpty(req.getPartSn())) {
                skuOrder.setPartSn(req.getPartSn());
                skuOrder.setIsSponsor("N");
            } else {
                skuOrder.setPartSn(UUIDUtils.getUUID());
                skuOrder.setIsSponsor("Y");
            }
            skuOrder.setPartStatus(SkuOrderStatusEnum.WAITING.getCode());
            skuOrder.setPartFinshTime(getWebExpireTime(secondPlatformSystemDeploy.getUnit(), secondPlatformSystemDeploy.getDetails().intValue(), order.getCreateTime()));
        }
        skuOrder.setAppletType(req.getAppletType());
        skuOrderDao.insert(skuOrder);
        SkuOrderDetail skuOrderDetail = new SkuOrderDetail();
        skuOrderDetail.setMerchantId(req.getMerchantId());
        skuOrderDetail.setSkuOrderId(skuOrder.getId());
        skuOrderDetail.setSkuId(req.getSkuId());
        skuOrderDetail.setSkuSalesInformationId(req.getSkuSalesInformationId());
        skuOrderDetail.setSupplierId(sku.getSupplierId());
        skuOrderDetail.setPrice(unitPrice);
        skuOrderDetail.setPayPrice(payPrice);
        skuOrderDetail.setCount(req.getCount());
        skuOrderDetail.setDeliveryWay(skuContent.getLogistics());
        skuOrderDetail.setIntegral(integral);
        skuOrderDetail.setIsRegion(isRegion);
        skuOrderDetailDao.insert(skuOrderDetail);
        if (skuContent.getLogistics().equals(DeliveryWayEnum.FULLREDUCTION.getCode())) {
            UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
            urbanFullReductionQuery.setCityId(req.getCityId());
            UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            if (urbanFullReductionDaoFirst == null) {
                urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            }
            if (payPrice < urbanFullReductionDaoFirst.getMoney()) {
                SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
                skuOrderDeliveryDemand.setSkuOrderId(skuOrder.getId());
                skuOrderDeliveryDemand.setMerchantId(merchant.getId());
                skuOrderDeliveryDemand.setPostage(urbanFullReductionDaoFirst.getFreight());
                skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.WAITING.getCode());
                skuOrderDeliveryDemand.setCreateTime(new Date());
                skuOrderDeliveryDemand.setLogistics(skuContent.getLogistics());
                skuOrderDeliveryDemandDao.insert(skuOrderDeliveryDemand);
                SkuOrderDetail updateSkuOrder = new SkuOrderDetail();
                updateSkuOrder.setId(skuOrderDetail.getId());
                updateSkuOrder.setIsHavingPostage("Y");
                skuOrderDetailDao.updateById(updateSkuOrder);
                freight = urbanFullReductionDaoFirst.getFreight();
            } else {
                SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
                skuOrderDeliveryDemand.setSkuOrderId(skuOrder.getId());
                skuOrderDeliveryDemand.setMerchantId(merchant.getId());
                skuOrderDeliveryDemand.setPostage(0.0);
                skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.PAY.getCode());
                skuOrderDeliveryDemand.setPostagePayTime(new Date());
                skuOrderDeliveryDemand.setCreateTime(new Date());
                skuOrderDeliveryDemand.setLogistics(skuContent.getLogistics());
                skuOrderDeliveryDemandDao.insert(skuOrderDeliveryDemand);
                SkuOrderDetail updateSkuOrder = new SkuOrderDetail();
                updateSkuOrder.setId(skuOrderDetail.getId());
                updateSkuOrder.setIsHavingPostage("Y");
                skuOrderDetailDao.updateById(updateSkuOrder);
            }
        }

        Order param = new Order();
        param.setId(order.getId());
        param.setTotalPrice(price > 0 ? price : 0);
        param.setPayPrice(payPrice > 0 ? payPrice : 0);
        orderDao.updateById(param);
        Order newOrder = orderDao.findById(order.getId());
        BeanUtils.copyProperties(orderResult, newOrder);
        orderResult.setTotalPrice(price + freight);
        orderResult.setPayPrice(payPrice + freight);
        orderResult.setOutOrderId(environment + OrderTypeEnum.SKU.getCode() + "-" + skuOrder.getId());
        Double finalPayPrice = payPrice;
        double finalPrice = price;
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Integer fengyongMerchantId = null;
                    Double fengyongProportion = 0.0;
                    Double fengxiaoProportion = null;
                    DailiMerchantQuery param = new DailiMerchantQuery();
                    param.setMobile(merchant.getMobile());
                    param.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
                    param.setIsEnable("Y");
                    DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(param);
                    if (dailiMerchant == null) {
                        throw BusinessException.build(ExceptionEnum.ERROR_1902);
                    }
                    if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(dailiMerchant.getRole())) {
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        fengxiaoProportion = dailiMerchant.getProportion();
                        fengyongMerchantId = dailiMerchant.getPid();
                    } else if (DailiMerchantRoleEnum.MERCHANT.getCode().equals(dailiMerchant.getRole())) {
                        fengyongMerchantId = Integer.parseInt(dailiMerchant.getPidPath().split(",")[0]);
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(secondMerchant.getRole())) {
                            DailiMerchant thirdMerchant = dailiMerchantDao.findById(secondMerchant.getPid());
                            if (!"Y".equals(thirdMerchant.getIsEnable())) {
                                throw BusinessException.build(ExceptionEnum.ERROR_1902);
                            }
                            fengxiaoProportion = secondMerchant.getProportion();
                        }
                    } else {
                        fengyongMerchantId = dailiMerchant.getId();
                    }
                    DailiMerchantSkuQuery dailiMerchantSkuQuery = new DailiMerchantSkuQuery();
                    dailiMerchantSkuQuery.setDailiMerchantId(fengyongMerchantId);
                    dailiMerchantSkuQuery.setSkuId(req.getSkuId());
                    DailiMerchantSku dailiMerchantSku = dailiMerchantSkuDao.findFirst(dailiMerchantSkuQuery);
                    if (dailiMerchantSku == null) {
                        throw BusinessException.build(ExceptionEnum.ERROR_1903);
                    }
                    fengyongProportion = dailiMerchantSku.getProportion();
                    if (regionalSkuSalesInformation != null && regionalSkuSalesInformation.getProportion() != null) {
                        fengyongProportion = regionalSkuSalesInformation.getProportion();
                    }
                    DailiOrder dailiOrder = new DailiOrder();
                    dailiOrder.setOrderId(skuOrderDetail.getId());
                    dailiOrder.setDailiMerchantId(dailiMerchant.getId());
                    dailiOrder.setDailiPidPath(dailiMerchant.getPidPath());
                    dailiOrder.setSkuId(req.getSkuId());
                    dailiOrder.setOrderAmount(finalPrice);
                    dailiOrder.setPayAmount(finalPayPrice);
                    double fengyongAmount = new BigDecimal(finalPayPrice + "").multiply(new BigDecimal(fengyongProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                    dailiOrder.setFengyongAmount(fengyongAmount);
                    if (fengxiaoProportion != null) {
                        double fenxiaoyuanAmount = new BigDecimal(fengyongAmount + "").multiply(new BigDecimal(fengxiaoProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                        dailiOrder.setFengxiaoyuanAmount(fenxiaoyuanAmount);
                        dailiOrder.setFengyongAmount(new BigDecimal(fengyongAmount + "").subtract(new BigDecimal(fenxiaoyuanAmount + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
                    }
                    dailiOrder.setCreateTime(new Date());
                    dailiOrder.setDate(DateUtil.date(new Date(), "yyyy-MM"));
                    dailiOrderDao.insert(dailiOrder);
                } catch (BusinessException e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                }
            }
        });
        return orderResult;
    }

    public Date getExpireTime(String uint, Integer details) {
        if (SystemDeployTimeEnum.DAY.getCode().equals(uint)) {
            return DateUtil.addDays(new Date(), -details);
        } else if (SystemDeployTimeEnum.HOUR.getCode().equals(uint)) {
            return DateUtil.addHour(new Date(), -details);
        } else if (SystemDeployTimeEnum.MINUTE.getCode().equals(uint)) {
            return DateUtil.addMinutes(new Date(), -details);
        }
        return null;
    }

    public Date getWebExpireTime(String uint, Integer details, Date date) {
        if (SystemDeployTimeEnum.DAY.getCode().equals(uint)) {
            return DateUtil.addDays(date, details);
        } else if (SystemDeployTimeEnum.HOUR.getCode().equals(uint)) {
            return DateUtil.addHour(date, details);
        } else if (SystemDeployTimeEnum.MINUTE.getCode().equals(uint)) {
            return DateUtil.addMinutes(date, details);
        }
        return null;
    }

    public Date getEnjoyEndTime(Date date) {
        int enjoyDay = Integer.parseInt(enjouyDay);
        int monthInteger = DateUtil.getMonthInteger(date);
        return DateUtil.setMinDate(DateUtil.getDate(DateUtil.getYear(), monthInteger + 1, enjoyDay));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderResult addOrderByCar(SkuOrderAddReq req) throws BusinessException {
        OrderResult orderResult = new OrderResult();
        List<String> skuNames = new ArrayList<>();
        Merchant merchant = merchantDao.findById(req.getMerchantId());
        if ("Y".equals(req.getIsByBalance())&&merchant.getBalance()<=0.0){
            throw new BusinessException(ExceptionEnum.ERROR_1714.getCode(), ExceptionEnum.ERROR_1714.getMessage());
        }
        PlatformSystemDeploy platformSystemDeploy = jfPlatformSystemDeploy();
        MerchantCity merchantCity = getMerchantCity(req.getMerchantCityId());
        Order order = new Order();
        order.setMerchantId(req.getMerchantId());
        order.setOrderType(SkuTypeEnum.SKU.getCode());
        order.setCreateTime(new Date());
        order.setMerchantCityId(req.getMerchantCityId());
        order.setReceiver(merchantCity.getReceiver());
        order.setReceiverMobile(merchantCity.getReceiverMobile());
        order.setAddress(merchantCity.getProvinceName() + merchantCity.getCityName() + merchantCity.getAreaName() + merchantCity.getAddress());
        orderDao.insert(order);
        //总价
        Double totalPrice = 0.0;
        //支付价格
        Double totalPayPrice = 0.0;
        //积分价格
        Double integerPrice = 0.0;
        //积分
        Integer integralPrice = 0;
        //积分
        Double unitPrice = 0.0;
        //商户积分
        Integer merchantIntegral = merchant.getIntegral();
        //
        Double fullReductionPrice = 0.0;
        List<SkuOrderDetail> skuOrderDetails = new ArrayList<>();
        List<SkuShopcar> skuShopcars = skuShopcarDao.findByIds(req.getSkuShopcarId());
        for (SkuShopcar skuShopcar : skuShopcars) {
            SkuOrderDetail skuOrderDetail = new SkuOrderDetail();
            ValidateBusinessException.assertTrue(req.getMerchantId().equals(skuShopcar.getMerchantId()), ExceptionEnum.ERROR_1853);
            Integer count = skuShopcar.getCount();
            Sku sku = skuDao.findById(skuShopcar.getSkuId());
            ValidateBusinessException.assertNonNull(sku, ExceptionEnum.ERROR_1701);
            ValidateBusinessException.assertFalse("N".equals(sku.getIsEnable()), ExceptionEnum.ERROR_1702);
            skuNames.add(sku.getTitle());
            SkuContent skuContent = skuContentDao.findBySkuId(skuShopcar.getSkuId());
            ValidateBusinessException.assertNonNull(skuContent, ExceptionEnum.ERROR_1701);
            SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuShopcar.getSkuSalesInformationId());
            ValidateBusinessException.assertNonNull(skuSalesInformation, ExceptionEnum.ERROR_1703);
            ValidateBusinessException.assertFalse(skuSalesInformation.getStock() < skuShopcar.getCount(), ExceptionEnum.ERROR_1816.getCode(), sku.getTitle() + (ExceptionEnum.ERROR_1816.getMessage()));
            Double price = new BigDecimal(skuSalesInformation.getPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            unitPrice = skuSalesInformation.getPrice();
            if (req.getCityId() != null) {
                RegionalSku regionalSku = regionalSkuDao.findBySkuId(skuShopcar.getSkuId());
                if (regionalSku != null) {
                    if ("N".equals(req.getIsByBalance()) && "Y".equals(regionalSku.getIsMembersExclusive())) {
                        throw new BusinessException(ExceptionEnum.ERROR_1713.getCode(), sku.getTitle() + "," + ExceptionEnum.ERROR_1713.getMessage());
                    }
                }
            }
            RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(merchantCity.getCityId(), req.getCityId(), skuShopcar.getSkuSalesInformationId(), sku.getTitle());
            if (regionalSkuSalesInformation != null) {
                price = new BigDecimal(regionalSkuSalesInformation.getRegionalPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                unitPrice = regionalSkuSalesInformation.getRegionalPrice();
                skuOrderDetail.setIsRegion("Y");
            }
            totalPrice += price;
            IntegerPrice ip = getIntegral(req.getIsUseIntegral(), price, merchant, skuContent, skuSalesInformation, regionalSkuSalesInformation);
            integralPrice = ip.getIntegral();
            integerPrice = ip.getIntegralPrice();
            //商户扣减积分
            merchantIntegral -= integralPrice;
            double payPrice = 0.0;
            if (price >= integerPrice) {
                payPrice = new BigDecimal(price).subtract(new BigDecimal(integerPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            }
            totalPayPrice += payPrice;
            ValidateBusinessException.assertFalse("Y".equals(skuContent.getIsSpellOrder()), ExceptionEnum.ERROR_1707);
            if (skuContent.getLogistics().equals(DeliveryWayEnum.FULLREDUCTION.getCode())) {
                fullReductionPrice += payPrice;
            }
            skuOrderDetail.setSkuId(skuShopcar.getSkuId());
            skuOrderDetail.setSkuSalesInformationId(skuShopcar.getSkuSalesInformationId());
            skuOrderDetail.setSupplierId(sku.getSupplierId());
            skuOrderDetail.setPrice(unitPrice);
            skuOrderDetail.setCount(skuShopcar.getCount());
            skuOrderDetail.setDeliveryWay(skuContent.getLogistics());
            skuOrderDetail.setTotalPrice(price);
            skuOrderDetail.setPayPrice(payPrice);
            skuOrderDetail.setTotalInteger(integralPrice);
            skuOrderDetail.setIntegral(integralPrice);
            skuOrderDetail.setMerchantId(req.getMerchantId());
            skuOrderDetails.add(skuOrderDetail);
        }
        Boolean isHavingPostage = false;
        Double freight = 0.0;
        if (fullReductionPrice > 0.0) {
            UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
            urbanFullReductionQuery.setCityId(req.getCityId());
            UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            if (urbanFullReductionDaoFirst == null) {
                urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            }
            if (fullReductionPrice < urbanFullReductionDaoFirst.getMoney()) {
                isHavingPostage = true;
                freight = urbanFullReductionDaoFirst.getFreight();
            }

        }
        Order param = new Order();
        param.setId(order.getId());
        param.setTotalPrice(totalPrice);
        param.setPayPrice(totalPayPrice);
        orderDao.updateById(param);
        Order newOrder = orderDao.findById(order.getId());
        BeanUtils.copyProperties(orderResult, newOrder);
        orderResult.setTotalPrice(totalPrice + freight);
        orderResult.setPayPrice(totalPayPrice + freight);
        List<SkuOrderDetail> skuOrderDetailsList = addSkuOrderByCar(req.getAppletType(), "Y".equals(req.getIsByBalance()) ? SkuOrderTypeEnum.BALANCE : SkuOrderTypeEnum.BUY, skuOrderDetails,
                order.getId(), req.getMerchantId(), freight, isHavingPostage, req.getCityId());
        orderResult.setOutOrderId(environment + OrderTypeEnum.CAR.getCode() + "-" + newOrder.getId());
        orderResult.setSkuNames(skuNames);
        skuShopcarDao.deleteByIds(req.getSkuShopcarId(), req.getMerchantId());

        //添加分佣信息
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Integer fengyongMerchantId = null;
                    Double fengyongProportion = 0.0;
                    Double fengxiaoProportion = null;
                    DailiMerchantQuery param = new DailiMerchantQuery();
                    param.setMobile(merchant.getMobile());
                    param.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
                    param.setIsEnable("Y");
                    DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(param);
                    if (dailiMerchant == null) {
                        throw BusinessException.build(ExceptionEnum.ERROR_1902);
                    }
                    if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(dailiMerchant.getRole())) {
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        fengxiaoProportion = dailiMerchant.getProportion();
                        fengyongMerchantId = dailiMerchant.getPid();
                    } else if (DailiMerchantRoleEnum.MERCHANT.getCode().equals(dailiMerchant.getRole())) {
                        fengyongMerchantId = Integer.parseInt(dailiMerchant.getPidPath().split(",")[0]);
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(secondMerchant.getRole())) {
                            DailiMerchant thirdMerchant = dailiMerchantDao.findById(secondMerchant.getPid());
                            if (!"Y".equals(thirdMerchant.getIsEnable())) {
                                throw BusinessException.build(ExceptionEnum.ERROR_1902);
                            }
                            fengxiaoProportion = secondMerchant.getProportion();
                        }
                    } else {
                        fengyongMerchantId = dailiMerchant.getId();
                    }
                    logger.info("aaaaaaaaaaaa");
                    for (SkuOrderDetail skuOrderDetail : skuOrderDetailsList) {
                        logger.info("skuOrderDetail" + JSONObject.toJSONString(skuOrderDetail));
                        DailiMerchantSkuQuery dailiMerchantSkuQuery = new DailiMerchantSkuQuery();
                        dailiMerchantSkuQuery.setDailiMerchantId(fengyongMerchantId);
                        dailiMerchantSkuQuery.setSkuId(skuOrderDetail.getSkuId());
                        DailiMerchantSku dailiMerchantSku = dailiMerchantSkuDao.findFirst(dailiMerchantSkuQuery);
                        if (dailiMerchantSku != null) {
                            fengyongProportion = dailiMerchantSku.getProportion();
                            RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(merchantCity.getCityId(), req.getCityId(), skuOrderDetail.getSkuSalesInformationId(), dailiMerchantSku.getTitle());
                            if (regionalSkuSalesInformation != null && regionalSkuSalesInformation.getProportion() != null) {
                                fengyongProportion = regionalSkuSalesInformation.getProportion();

                            }
                            DailiOrder dailiOrder = new DailiOrder();
                            dailiOrder.setOrderId(skuOrderDetail.getId());
                            dailiOrder.setDailiMerchantId(dailiMerchant.getId());
                            dailiOrder.setDailiPidPath(dailiMerchant.getPidPath());
                            dailiOrder.setSkuId(skuOrderDetail.getSkuId());
                            dailiOrder.setOrderAmount(skuOrderDetail.getPrice());
                            dailiOrder.setPayAmount(skuOrderDetail.getPayPrice());
                            double fengyongAmount = new BigDecimal(skuOrderDetail.getPayPrice() + "").multiply(new BigDecimal(fengyongProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                            dailiOrder.setFengyongAmount(fengyongAmount);
                            if (fengxiaoProportion != null) {
                                double fenxiaoyuanAmount = new BigDecimal(fengyongAmount + "").multiply(new BigDecimal(fengxiaoProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                                dailiOrder.setFengxiaoyuanAmount(fenxiaoyuanAmount);
                                dailiOrder.setFengyongAmount(new BigDecimal(fengyongAmount + "").subtract(new BigDecimal(fenxiaoyuanAmount + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
                            }
                            dailiOrder.setCreateTime(new Date());
                            dailiOrder.setDate(DateUtil.date(new Date(), "yyyy-MM"));
                            dailiOrderDao.insert(dailiOrder);
                        }
                    }
                } catch (BusinessException e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                }
            }
        });
        return orderResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payOrderByBalance(OrderResult orderResult) throws BusinessException {
        Order order = orderDao.findById(orderResult.getId());
        Integer deleteBalance = merchantDao.deleteBalance(orderResult.getMerchantId(), orderResult.getPayPrice());
        if (deleteBalance > 0) {
            Integer orderId = Integer.parseInt(orderResult.getOutOrderId().split("-")[1]);
            SkuOrder skuOrder = skuOrderDao.findById(orderId);
            OrderBalance orderBalance = new OrderBalance();
            orderBalance.setMerchantId(orderResult.getMerchantId());
            orderBalance.setPayOrderId(order.getId());
            orderBalance.setBalanceMoney(-order.getPayPrice());
            orderBalance.setRechargeType("shopping");
            orderBalance.setNotes("购买商品，订单id:" + orderId);
            orderBalance.setStatus(SkuOrderStatusEnum.SUCCESS.getCode());
            orderBalance.setCreateTime(new Date());
            orderBalanceDao.insert(orderBalance);
            SkuOrder newBO = new SkuOrder();
            newBO.setStatus(SkuOrderStatusEnum.PAY.getCode());
            newBO.setPayTime(new Date());
            newBO.setId(orderId);
            newBO.setIsPay("Y");
            skuOrderDao.updateById(newBO);
            SkuOrderDetailQuery param = new SkuOrderDetailQuery();
            param.setSkuOrderId(orderId);
            List<SkuOrderDetail> skuOrderDetails = skuOrderDetailDao.list(param);
            for (SkuOrderDetail skuOrderDetail : skuOrderDetails) {
                Integer integer = skuSalesInformationDao.deleteStock(skuOrderDetail.getSkuSalesInformationId(), skuOrderDetail.getCount());
                ValidateBusinessException.assertTrue(integer > 0, ExceptionEnum.ERROR_1826.getCode(), skuOrderDetail.getSkuSalesInformationId() + "," + ExceptionEnum.ERROR_1826.getMessage());
                if (StringUtils.isNotEmpty(skuOrder.getPartSn())) {
                    SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
                    skuOrderQuery.setPartSn(skuOrder.getPartSn());
                    skuOrderQuery.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
                    List<SkuOrder> list = skuOrderDao.list(skuOrderQuery);
                    SkuContent skuContent = skuContentDao.findBySkuId(skuOrderDetail.getSkuId());
                    if (list.size() >= skuContent.getSpellOrderPeople()) {
                        skuOrderDao.updateByPartSn(skuOrder.getPartSn());
                    }
                }
            }

            if (skuOrder.getIntegral() > 0) {
                Merchant before = merchantDao.findById(skuOrder.getMerchantId());
                Integer integer1 = merchantDao.deleteIntegral(skuOrder.getMerchantId(), skuOrder.getIntegral());
                Merchant after = merchantDao.findById(skuOrder.getMerchantId());
                ValidateBusinessException.assertTrue(integer1 > 0, ExceptionEnum.ERROR_1827.getCode(), skuOrder.getId() + "," + ExceptionEnum.ERROR_1827.getMessage());
                MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
                merchantIntegralLog.setMerchantId(skuOrder.getMerchantId());
                merchantIntegralLog.setOperation(IntegralOperationEnum.DEDUCTION.getCode());
                merchantIntegralLog.setBeforeIntegral(before.getIntegral());
                merchantIntegralLog.setAfterIntegral(after.getIntegral());
                merchantIntegralLog.setCreateTime(new Date());
                merchantIntegralLogDao.insert(merchantIntegralLog);
            }
            SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
            skuOrderDeliveryDemand.setLogistics(DeliveryWayEnum.FULLREDUCTION.getCode());
            skuOrderDeliveryDemand.setSkuOrderId(skuOrder.getId());
            skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.PAY.getCode());
            skuOrderDeliveryDemand.setPostagePayTime(new Date());
            skuOrderDeliveryDemandDao.updateBySkuOrderId(skuOrderDeliveryDemand);
        } else {
            throw new BusinessException(ExceptionEnum.ERROR_1415.getCode(), ExceptionEnum.ERROR_1415.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payCarOrderByBalance(OrderResult orderResult) throws BusinessException {
        Order order = orderDao.findById(orderResult.getId());
        Integer deleteBalance = merchantDao.deleteBalance(orderResult.getMerchantId(), orderResult.getPayPrice());
        if (deleteBalance > 0) {
            SkuOrder newBO = new SkuOrder();
            newBO.setStatus(SkuOrderStatusEnum.PAY.getCode());
            newBO.setPayTime(new Date());
            newBO.setOrderId(orderResult.getId());
            newBO.setIsPay("Y");
            skuOrderDao.updateByOrderId(newBO);
            List<SkuOrder> skuOrders = skuOrderDao.getListByOrderId(InquireOrderStatusEnum.CANCEL.getCode(), orderResult.getId());
            String orderIds="";
            for (SkuOrder skuOrder : skuOrders) {
                orderIds=orderIds+","+skuOrder.getId();
                SkuOrderDetailQuery param = new SkuOrderDetailQuery();
                param.setSkuOrderId(skuOrder.getId());
                List<SkuOrderDetail> skuOrderDetails = skuOrderDetailDao.list(param);
                for (SkuOrderDetail skuOrderDetail : skuOrderDetails) {
                    Integer integer = skuSalesInformationDao.deleteStock(skuOrderDetail.getSkuSalesInformationId(), skuOrderDetail.getCount());
                    ValidateBusinessException.assertTrue(integer > 0, ExceptionEnum.ERROR_1826.getCode(), skuOrderDetail.getSkuSalesInformationId() + "," + ExceptionEnum.ERROR_1826.getMessage());
                    //积分大于0才去扣减
                    if (skuOrderDetail.getIntegral() > 0) {
                        Merchant before = merchantDao.findById(skuOrder.getMerchantId());
                        Integer integer1 = merchantDao.deleteIntegral(skuOrderDetail.getMerchantId(), skuOrderDetail.getIntegral());
                        Merchant after = merchantDao.findById(skuOrder.getMerchantId());
                        ValidateBusinessException.assertTrue(integer1 > 0, ExceptionEnum.ERROR_1827.getCode(), skuOrderDetail.getSkuSalesInformationId() + "," + ExceptionEnum.ERROR_1827.getMessage());
                        MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
                        merchantIntegralLog.setMerchantId(skuOrder.getMerchantId());
                        merchantIntegralLog.setOperation(IntegralOperationEnum.DEDUCTION.getCode());
                        merchantIntegralLog.setBeforeIntegral(before.getIntegral());
                        merchantIntegralLog.setAfterIntegral(after.getIntegral());
                        merchantIntegralLog.setCreateTime(new Date());
                        merchantIntegralLogDao.insert(merchantIntegralLog);
                    }
                    SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
                    skuOrderDeliveryDemand.setLogistics(DeliveryWayEnum.FULLREDUCTION.getCode());
                    skuOrderDeliveryDemand.setSkuOrderId(skuOrder.getId());
                    skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.PAY.getCode());
                    skuOrderDeliveryDemand.setPostagePayTime(new Date());
                    skuOrderDeliveryDemandDao.updateBySkuOrderId(skuOrderDeliveryDemand);
                }
            }
            OrderBalance orderBalance = new OrderBalance();
            orderBalance.setMerchantId(orderResult.getMerchantId());
            orderBalance.setPayOrderId(order.getId());
            orderBalance.setBalanceMoney(-order.getPayPrice());
            orderBalance.setRechargeType("shopping");
            orderBalance.setNotes("购买商品，订单id:" + orderIds);
            orderBalance.setStatus(SkuOrderStatusEnum.SUCCESS.getCode());
            orderBalance.setCreateTime(new Date());
            orderBalanceDao.insert(orderBalance);
        } else {
            throw new BusinessException(ExceptionEnum.ERROR_1415.getCode(), ExceptionEnum.ERROR_1415.getMessage());
        }
    }

    @Override
    public OrderResult addOrderCarByOffline(SkuOrderAddReq req) throws BusinessException {
        //查询商户信息
        MerchantQuery param = new MerchantQuery();
        param.setMobile(req.getMobile());
        param.setIsEnable("Y");
        //商户信息
        Merchant merchant = merchantDao.findFirst(param);
        if (merchant == null) {
            insertMerchant(req.getMobile());
        }
        merchant = merchantDao.findFirst(param);
        //分销员信息
        Merchant distributor = merchantDao.findById(req.getPlaceMerchantId());
        //判断商户是否属于该分销员
        isMerchant(req.getMobile(), distributor);
        OrderResult orderResult = new OrderResult();
        List<String> skuNames = new ArrayList<>();
        MerchantCity merchantCity = getMerchantCity(req.getMerchantCityId());
        Order order = new Order();
        order.setMerchantId(merchant.getId());
        order.setOrderType(SkuTypeEnum.SKU.getCode());
        order.setCreateTime(new Date());
        order.setMerchantCityId(req.getMerchantCityId());
        order.setReceiver(merchantCity.getReceiver());
        order.setReceiverMobile(merchantCity.getReceiverMobile());
        order.setAddress(merchantCity.getProvinceName() + merchantCity.getCityName() + merchantCity.getAreaName() + merchantCity.getAddress());
        order.setPlaceMerchantId(req.getPlaceMerchantId());
        orderDao.insert(order);
        //总价
        Double totalPrice = 0.0;
        //支付价格
        Double totalPayPrice = 0.0;
        //积分价格
        Double integerPrice = 0.0;
        //线下支付价格
        Double realityPrice = 0.0;
        //积分
        Integer integralPrice = 0;
        //积分
        Double unitPrice = 0.0;
        //商户积分
        Integer merchantIntegral = merchant.getIntegral();
        //
        Double fullReductionPrice = 0.0;
        List<SkuOrderDetail> skuOrderDetails = new ArrayList<>();
        List<SkuShopcar> skuShopcars = skuShopcarDao.findByIds(req.getSkuShopcarId());
        for (SkuShopcar skuShopcar : skuShopcars) {
            SkuOrderDetail skuOrderDetail = new SkuOrderDetail();
            ValidateBusinessException.assertTrue(distributor.getId().equals(skuShopcar.getMerchantId()), ExceptionEnum.ERROR_1853);
            Integer count = skuShopcar.getCount();
            Sku sku = skuDao.findById(skuShopcar.getSkuId());
            ValidateBusinessException.assertNonNull(sku, ExceptionEnum.ERROR_1701);
            ValidateBusinessException.assertFalse("N".equals(sku.getIsEnable()), ExceptionEnum.ERROR_1702);
            skuNames.add(sku.getTitle());
            SkuContent skuContent = skuContentDao.findBySkuId(skuShopcar.getSkuId());
            ValidateBusinessException.assertNonNull(skuContent, ExceptionEnum.ERROR_1701);
            SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuShopcar.getSkuSalesInformationId());
            ValidateBusinessException.assertNonNull(skuSalesInformation, ExceptionEnum.ERROR_1703);
            ValidateBusinessException.assertFalse(skuSalesInformation.getStock() < skuShopcar.getCount(), ExceptionEnum.ERROR_1816.getCode(), sku.getTitle() + (ExceptionEnum.ERROR_1816.getMessage()));
            Double price = new BigDecimal(skuSalesInformation.getPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            unitPrice = skuSalesInformation.getPrice();
            RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(merchantCity.getCityId(), req.getCityId(), skuShopcar.getSkuSalesInformationId(), sku.getTitle());
            if (regionalSkuSalesInformation != null) {
                price = new BigDecimal(regionalSkuSalesInformation.getRegionalPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                unitPrice = regionalSkuSalesInformation.getRegionalPrice();
                skuOrderDetail.setIsRegion("Y");
            }
            List<SkuRealityPriceReq> skuRealityPriceReqs = req.getSkuRealityPriceReqs();
            if (skuRealityPriceReqs != null && skuRealityPriceReqs.size() > 0) {
                Map<Integer, SkuRealityPriceReq> skuRealityPriceReqMap = skuRealityPriceReqs.stream().collect(Collectors.toMap(SkuRealityPriceReq::getSkuSalesInformationId, i -> i));
                SkuRealityPriceReq skuRealityPriceReq = skuRealityPriceReqMap.get(skuShopcar.getSkuSalesInformationId());
                if (skuRealityPriceReq != null) {
                    price = skuRealityPriceReq.getRealityPrice() * count;
                    realityPrice = skuRealityPriceReq.getRealityPrice();
                }
            }
            totalPrice += price;
            IntegerPrice ip = getIntegral(req.getIsUseIntegral(), price, merchant, skuContent, skuSalesInformation, regionalSkuSalesInformation);
            integralPrice = ip.getIntegral();
            integerPrice = ip.getIntegralPrice();
            //商户扣减积分
            merchantIntegral -= integralPrice;
            double payPrice = 0.0;
            if (price >= integerPrice) {
                payPrice = new BigDecimal(price).subtract(new BigDecimal(integerPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            }
            totalPayPrice += payPrice;
            ValidateBusinessException.assertFalse("Y".equals(skuContent.getIsSpellOrder()), ExceptionEnum.ERROR_1707);
            if (skuContent.getLogistics().equals(DeliveryWayEnum.FULLREDUCTION.getCode())) {
                fullReductionPrice += payPrice;
            }
            skuOrderDetail.setSkuId(skuShopcar.getSkuId());
            skuOrderDetail.setSkuSalesInformationId(skuShopcar.getSkuSalesInformationId());
            skuOrderDetail.setSupplierId(sku.getSupplierId());
            skuOrderDetail.setPrice(unitPrice);
            skuOrderDetail.setCount(skuShopcar.getCount());
            skuOrderDetail.setDeliveryWay(skuContent.getLogistics());
            skuOrderDetail.setTotalPrice(price);
            skuOrderDetail.setPayPrice(payPrice);
            skuOrderDetail.setTotalInteger(integralPrice);
            skuOrderDetail.setIntegral(integralPrice);
            skuOrderDetail.setMerchantId(merchant.getId());
            skuOrderDetail.setRealityPrice(realityPrice);
            skuOrderDetails.add(skuOrderDetail);
        }
        Boolean isHavingPostage = false;
        Double freight = 0.0;
        if (fullReductionPrice > 0.0) {
            UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
            urbanFullReductionQuery.setCityId(req.getCityId());
            UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            if (urbanFullReductionDaoFirst == null) {
                urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            }
            if (fullReductionPrice < urbanFullReductionDaoFirst.getMoney()) {
                isHavingPostage = true;
                freight = urbanFullReductionDaoFirst.getFreight();
            }

        }
        Order order1 = new Order();
        order1.setId(order.getId());
        order1.setTotalPrice(totalPayPrice);
        order1.setPayPrice(totalPayPrice);
        orderDao.updateById(order1);
        Order newOrder = orderDao.findById(order.getId());
        BeanUtils.copyProperties(orderResult, newOrder);
        orderResult.setTotalPrice(totalPrice + freight);
        orderResult.setPayPrice(totalPayPrice + freight);
        List<SkuOrderDetail> skuOrderDetailsList = addSkuOrderByCar(req.getAppletType(), SkuOrderTypeEnum.OFFLINE, skuOrderDetails,
                order.getId(), merchant.getId(), freight, isHavingPostage, req.getCityId());
        orderResult.setOutOrderId(environment + OrderTypeEnum.CAR.getCode() + "-" + newOrder.getId());
        orderResult.setSkuNames(skuNames);
        skuShopcarDao.deleteByIds(req.getSkuShopcarId(), distributor.getId());

        //添加分佣信息
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Integer fengyongMerchantId = null;
                    Double fengyongProportion = 0.0;
                    Double fengxiaoProportion = null;
                    DailiMerchantQuery param = new DailiMerchantQuery();
                    param.setMobile(distributor.getMobile());
                    param.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
                    param.setIsEnable("Y");
                    DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(param);
                    if (dailiMerchant == null) {
                        throw BusinessException.build(ExceptionEnum.ERROR_1902);
                    }
                    if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(dailiMerchant.getRole())) {
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        fengxiaoProportion = dailiMerchant.getProportion();
                        fengyongMerchantId = dailiMerchant.getPid();
                    } else if (DailiMerchantRoleEnum.MERCHANT.getCode().equals(dailiMerchant.getRole())) {
                        fengyongMerchantId = Integer.parseInt(dailiMerchant.getPidPath().split(",")[0]);
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(secondMerchant.getRole())) {
                            DailiMerchant thirdMerchant = dailiMerchantDao.findById(secondMerchant.getPid());
                            if (!"Y".equals(thirdMerchant.getIsEnable())) {
                                throw BusinessException.build(ExceptionEnum.ERROR_1902);
                            }
                            fengxiaoProportion = secondMerchant.getProportion();
                        }
                    } else {
                        fengyongMerchantId = dailiMerchant.getId();
                    }
                    for (SkuOrderDetail skuOrderDetail : skuOrderDetailsList) {
                        logger.info("skuOrderDetail" + JSONObject.toJSONString(skuOrderDetail));
                        DailiMerchantSkuQuery dailiMerchantSkuQuery = new DailiMerchantSkuQuery();
                        dailiMerchantSkuQuery.setDailiMerchantId(fengyongMerchantId);
                        dailiMerchantSkuQuery.setSkuId(skuOrderDetail.getSkuId());
                        DailiMerchantSku dailiMerchantSku = dailiMerchantSkuDao.findFirst(dailiMerchantSkuQuery);
                        if (dailiMerchantSku != null) {
                            fengyongProportion = dailiMerchantSku.getProportion();
                            RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(merchantCity.getCityId(), req.getCityId(), skuOrderDetail.getSkuSalesInformationId(), dailiMerchantSku.getTitle());
                            if (regionalSkuSalesInformation != null && regionalSkuSalesInformation.getProportion() != null) {
                                fengyongProportion = regionalSkuSalesInformation.getProportion();

                            }
                            DailiOrder dailiOrder = new DailiOrder();
                            dailiOrder.setOrderId(skuOrderDetail.getId());
                            dailiOrder.setDailiMerchantId(dailiMerchant.getId());
                            dailiOrder.setDailiPidPath(dailiMerchant.getPidPath());
                            dailiOrder.setSkuId(skuOrderDetail.getSkuId());
                            dailiOrder.setOrderAmount(skuOrderDetail.getPrice());
                            dailiOrder.setPayAmount(skuOrderDetail.getPayPrice());
                            double fengyongAmount = new BigDecimal(skuOrderDetail.getPayPrice() + "").multiply(new BigDecimal(fengyongProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                            dailiOrder.setFengyongAmount(fengyongAmount);
                            if (fengxiaoProportion != null) {
                                double fenxiaoyuanAmount = new BigDecimal(fengyongAmount + "").multiply(new BigDecimal(fengxiaoProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                                dailiOrder.setFengxiaoyuanAmount(fenxiaoyuanAmount);
                                dailiOrder.setFengyongAmount(new BigDecimal(fengyongAmount + "").subtract(new BigDecimal(fenxiaoyuanAmount + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
                            }
                            dailiOrder.setCreateTime(new Date());
                            dailiOrder.setDate(DateUtil.date(new Date(), "yyyy-MM"));
                            dailiOrderDao.insert(dailiOrder);
                        }
                    }
                } catch (BusinessException e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                }
            }
        });
        return orderResult;
    }

    @Override
    public SkuTotalResult getSkuTotalResult(Integer orderId) throws BusinessException {
        SkuTotalResult skuTotalResult = new SkuTotalResult();
        Order order = orderDao.findById(orderId);
        skuTotalResult.setAddress(order.getAddress());
        skuTotalResult.setReceiver(order.getReceiver());
        skuTotalResult.setReceiverMobile(order.getReceiver());
        skuTotalResult.setOrderId(orderId);
        skuTotalResult.setCreateTime(order.getCreateTime());
        skuTotalResult.setTotalPrice(order.getTotalPrice());
        skuTotalResult.setTotalPayPrice(order.getPayPrice());
        skuTotalResult.setRealityPrice(order.getRealityPrice());
        Merchant merchant = merchantDao.findById(order.getMerchantId());
        skuTotalResult.setMerchantName(merchant.getName());
        skuTotalResult.setMerchantMobile(merchant.getMobile());
        Merchant distributor = merchantDao.findById(order.getPlaceMerchantId());
        if (distributor != null) {
            skuTotalResult.setDistributorName(distributor.getName());
            skuTotalResult.setDistributorMobile(distributor.getMobile());
        }
        Double fengyongAmount = 0.0;
        Double fengxiaoyuanAmount = 0.0;
        List<SkuOrderResult> skuOrderResultList = new ArrayList<>();
        SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
        skuOrderQuery.setOrderId(orderId);
        List<Integer> skuOrderId = skuOrderDao.getSkuOrderId(skuOrderQuery);
        Double totalPostagePrice = 0.0;
        for (Integer integer : skuOrderId) {
            SkuOrderResult skuOrderResult = new SkuOrderResult();
            SkuOrder skuOrder = skuOrderDao.findByIdAndMerchantId(integer, order.getMerchantId());
            ValidateBusinessException.assertNonNull(skuOrder, ExceptionEnum.ERROR_1801);
            skuTotalResult.setStatus(skuOrder.getStatus());
            BeanUtils.copyProperties(skuOrderResult, skuOrder);
            SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
            skuOrderDetailQuery.setSkuOrderId(skuOrderResult.getId());
            List<SkuOrderDetail> list = skuOrderDetailDao.list(skuOrderDetailQuery);
            List<SkuOrderDetailResult> skuOrderDetailResults = DTOUtils.convertList(list, SkuOrderDetailResult.class);
            Double postagePrice = 0.0;
            for (SkuOrderDetailResult skuOrderDetailResult : skuOrderDetailResults) {
                Sku sku = skuDao.findById(skuOrderDetailResult.getSkuId());
                if (sku != null) {
                    skuOrderDetailResult.setSkuName(sku.getTitle());
                    SkuContent skuContent = skuContentDao.findBySkuId(skuOrderDetailResult.getSkuId());
                    if (skuContent != null) {
                        skuOrderDetailResult.setCover(skuContent.getCover());
                    }
                    SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuOrderDetailResult.getSkuSalesInformationId());
                    if (skuSalesInformation != null) {
                        if (StringUtils.isNotBlank(skuSalesInformation.getCover())) {
                            skuOrderDetailResult.setCover(skuSalesInformation.getCover());
                        }
                    }
                    SkuCategory skuCategory = skuCategoryDao.findById(sku.getCategoryId());
                    if (skuCategory != null)
                        skuOrderDetailResult.setCategoryName(skuCategory.getName());
                }
                SkuOrderDeliveryDemandQuery param = new SkuOrderDeliveryDemandQuery();
                param.setSkuOrderId(skuOrderDetailResult.getSkuOrderId());
                param.setMerchantId(order.getMerchantId());
                param.setNoPostageStatus(SkuOrderStatusEnum.CANCEL.getCode());
                SkuOrderDeliveryDemand skuOrderDeliveryDemand = skuOrderDeliveryDemandDao.findFirst(param);
                if (skuOrderDeliveryDemand != null) {
                    if (DeliveryWayEnum.FULLREDUCTION.getCode().equals(skuOrderDeliveryDemand.getLogistics())) {
                        postagePrice += skuOrderDeliveryDemand.getPostage();
                    }
                    SkuOrderDeliveryDemandResult skuOrderDeliveryDemandResult = new SkuOrderDeliveryDemandResult();
                    BeanUtils.copyProperties(skuOrderDeliveryDemandResult, skuOrderDeliveryDemand);
                    skuOrderResult.setSkuOrderDeliveryDemandResult(skuOrderDeliveryDemandResult);
                }
                DailiOrderQuery dailiOrderQuery = new DailiOrderQuery();
                dailiOrderQuery.setOrderId(skuOrderDetailResult.getId());
                DailiOrder dailiOrder = dailiOrderDao.findFirst(dailiOrderQuery);
                if (dailiOrder != null) {
                    fengyongAmount += dailiOrder.getFengyongAmount();
                    if (dailiOrder.getFengxiaoyuanAmount() != null) {
                        fengxiaoyuanAmount += dailiOrder.getFengxiaoyuanAmount();
                    }
                }

            }
            totalPostagePrice += postagePrice;
            skuOrderResult.setSkuPrice(skuOrderResult.getPayPrice());
            skuOrderResult.setPostagePrice(postagePrice);
            skuOrderResult.setPayPrice(postagePrice + skuOrderResult.getPayPrice());
            if (SkuOrderStatusEnum.WAITING.getCode().equals(skuOrderResult.getStatus())) {
                PlatformSystemDeploy platformSystemDeploy = getPlatformSystemDeploy(SkuTypeEnum.SKU.getCode(), SkuOrderStatusEnum.WAITING.getCode());
                if (platformSystemDeploy != null) {
                    skuOrderResult.setExpireTime(getWebExpireTime(platformSystemDeploy.getUnit(), platformSystemDeploy.getDetails().intValue(), order.getCreateTime()));
                }
            }
            skuOrderResult.setSkuOrderDetailResults(skuOrderDetailResults);
            skuOrderResultList.add(skuOrderResult);
        }
        if (SkuOrderStatusEnum.WAITING.getCode().equals(skuTotalResult.getStatus())) {
            PlatformSystemDeploy platformSystemDeploy = getPlatformSystemDeploy(SkuTypeEnum.SKU.getCode(), SkuOrderStatusEnum.WAITING.getCode());
            if (platformSystemDeploy != null) {
                skuTotalResult.setExpireTime(getWebExpireTime(platformSystemDeploy.getUnit(), platformSystemDeploy.getDetails().intValue(), order.getCreateTime()));
            }
        }
        skuTotalResult.setFengyongAmount(fengyongAmount);
        skuTotalResult.setFengxiaoyuanAmount(fengxiaoyuanAmount);
        skuTotalResult.setSkuOrderResultList(skuOrderResultList);
        skuTotalResult.setTotalPostagePrice(totalPostagePrice);
        skuTotalResult.setTotalPayPrice(order.getPayPrice() + totalPostagePrice);
        return skuTotalResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmOrder(Integer orderId, String mobile, String smsCode) throws BusinessException {
        MerchantQuery merchantQuery = new MerchantQuery();
        merchantQuery.setMobile(mobile);
        Merchant merchant = merchantDao.findFirst(merchantQuery);
        Integer merchantId = merchant.getId();
        // 校验验证码
        boolean isValid = smsCodeService.validateSmsCode(merchant.getMobile(), smsCode, SmsSourceEnum.USER_CONFIRM);
        if (!isValid) {
            throw BusinessException.build(ExceptionEnum.ERROR_1210);
        }
        OrderQuery query = new OrderQuery();
        query.setId(orderId);
        query.setMerchantId(merchantId);
        Order order = orderDao.findFirst(query);
        ValidateBusinessException.assertNonNull(order, ExceptionEnum.ERROR_1801);
        DailiMerchantQuery dailiMerchantQuery = new DailiMerchantQuery();
        dailiMerchantQuery.setMobile(merchant.getMobile());
        DailiMerchant dailiMerchantMerchant = dailiMerchantDao.findFirst(dailiMerchantQuery);
        if (dailiMerchantMerchant == null) {
            DailiMerchant insertDailiMerchant = new DailiMerchant();
            insertDailiMerchant.setMobile(merchant.getMobile());
            insertDailiMerchant.setRole(DailiMerchantRoleEnum.MERCHANT.getCode());
            Merchant merchant1 = merchantDao.findById(order.getPlaceMerchantId());
            DailiMerchantQuery dailiMerchantQuery1 = new DailiMerchantQuery();
            dailiMerchantQuery1.setMobile(merchant1.getMobile());
            DailiMerchant distributor = dailiMerchantDao.findFirst(dailiMerchantQuery1);
            insertDailiMerchant.setPid(distributor.getId());
            insertDailiMerchant.setPidPath(distributor.getPidPath());
            insertDailiMerchant.setIsEnable("Y");
            insertDailiMerchant.setCreateTime(new Date());
            insertDailiMerchant.setStatus("success");
            dailiMerchantDao.insert(insertDailiMerchant);
            DailiMerchant updateMerchant = new DailiMerchant();
            updateMerchant.setId(insertDailiMerchant.getId());
            updateMerchant.setPidPath(distributor.getPidPath() + insertDailiMerchant.getId() + ",");
            dailiMerchantDao.updateById(updateMerchant);
        }
        dailiMerchantMerchant = dailiMerchantDao.findFirst(dailiMerchantQuery);
        SkuOrder newBO = new SkuOrder();
        newBO.setStatus(SkuOrderStatusEnum.SUCCESS.getCode());
        newBO.setPayTime(new Date());
        newBO.setOrderId(orderId);
        newBO.setIsPay("Y");
        skuOrderDao.updateByOrderId(newBO);
        List<SkuOrder> skuOrders = skuOrderDao.getListByOrderId(InquireOrderStatusEnum.CANCEL.getCode(), orderId);
        for (SkuOrder skuOrder : skuOrders) {
            SkuOrderDetailQuery param = new SkuOrderDetailQuery();
            param.setSkuOrderId(skuOrder.getId());
            List<SkuOrderDetail> skuOrderDetails = skuOrderDetailDao.list(param);
            for (SkuOrderDetail skuOrderDetail : skuOrderDetails) {
                Integer integer = skuSalesInformationDao.deleteStock(skuOrderDetail.getSkuSalesInformationId(), skuOrderDetail.getCount());
                ValidateBusinessException.assertTrue(integer > 0, ExceptionEnum.ERROR_1826.getCode(), skuOrderDetail.getSkuSalesInformationId() + "," + ExceptionEnum.ERROR_1826.getMessage());
                //积分大于0才去扣减
                if (skuOrderDetail.getIntegral() > 0) {
                    Merchant before = merchantDao.findById(skuOrder.getMerchantId());
                    Integer integer1 = merchantDao.deleteIntegral(skuOrderDetail.getMerchantId(), skuOrderDetail.getIntegral());
                    Merchant after = merchantDao.findById(skuOrder.getMerchantId());
                    ValidateBusinessException.assertTrue(integer1 > 0, ExceptionEnum.ERROR_1827.getCode(), skuOrderDetail.getSkuSalesInformationId() + "," + ExceptionEnum.ERROR_1827.getMessage());
                    MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
                    merchantIntegralLog.setMerchantId(skuOrder.getMerchantId());
                    merchantIntegralLog.setOperation(IntegralOperationEnum.DEDUCTION.getCode());
                    merchantIntegralLog.setBeforeIntegral(before.getIntegral());
                    merchantIntegralLog.setAfterIntegral(after.getIntegral());
                    merchantIntegralLog.setCreateTime(new Date());
                    merchantIntegralLogDao.insert(merchantIntegralLog);
                }
                SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
                skuOrderDeliveryDemand.setLogistics(DeliveryWayEnum.FULLREDUCTION.getCode());
                skuOrderDeliveryDemand.setSkuOrderId(skuOrder.getId());
                skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.PAY.getCode());
                skuOrderDeliveryDemand.setPostagePayTime(new Date());
                skuOrderDeliveryDemandDao.updateBySkuOrderId(skuOrderDeliveryDemand);
                DailiOrderQuery dailiOrderQuery = new DailiOrderQuery();
                dailiOrderQuery.setOrderId(skuOrderDetail.getId());
                DailiOrder dailiOrder = dailiOrderDao.findFirst(dailiOrderQuery);
                if (dailiOrder != null) {
                    DailiOrder updateDailiOrder = new DailiOrder();
                    updateDailiOrder.setId(dailiOrder.getId());
                    updateDailiOrder.setDailiMerchantId(dailiMerchantMerchant.getId());
                    updateDailiOrder.setDailiPidPath(dailiMerchantMerchant.getPidPath());
                    dailiOrderDao.updateById(updateDailiOrder);
                }
            }
        }
    }

    public void insertMerchant(String mobile) {
        Merchant insertMerchant = new Merchant();
        insertMerchant.setName(StringUtil.mobileNick(mobile));
        insertMerchant.setMobile(mobile);
        String password = mobile.substring(mobile.length() - 6);
        insertMerchant.setPassword(PasswordUtil.getPass(password));
        insertMerchant.setBuyPermission(SkuTypeEnum.SKU.getCode());
        insertMerchant.setIntegral(0);
        insertMerchant.setIdNumber("");
        insertMerchant.setPid(0);
        String uuid = UUIDUtils.getUUID();
        insertMerchant.setUuid(uuid);
        insertMerchant.setCreateTime(new Date());
        insertMerchant.setIsEnable("Y");
        insertMerchant.setBalance(0.0);
        merchantDao.insert(insertMerchant);
    }

    private void isMerchant(String mobile, Merchant distributor) throws BusinessException {
        DailiMerchantQuery distributorQuery = new DailiMerchantQuery();
        distributorQuery.setMobile(distributor.getMobile());
        DailiMerchant distributorMerchant = dailiMerchantDao.findFirst(distributorQuery);
        DailiMerchantQuery dailiMerchantQuery = new DailiMerchantQuery();
        dailiMerchantQuery.setMobile(mobile);
        DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(dailiMerchantQuery);
        if (dailiMerchant != null) {
            if (!DailiMerchantRoleEnum.MERCHANT.getCode().equals(dailiMerchant.getRole())) {
                throw BusinessException.build(ExceptionEnum.ERROR_1911);
            }

            if (!dailiMerchant.getPid().equals(distributorMerchant.getId())) {
                DailiMerchant dailiMerchantDaoById = dailiMerchantDao.findById(dailiMerchant.getPid());
                MerchantQuery merchantQuery = new MerchantQuery();
                merchantQuery.setMobile(dailiMerchantDaoById.getMobile());
                Merchant first = merchantDao.findFirst(merchantQuery);
                String message = ExceptionEnum.ERROR_1910.getMessage();
                String xxx = message.replaceAll("XXX", first.getName());
                throw BusinessException.build(ExceptionEnum.ERROR_1910.getCode(), xxx);
            }
        }
    }

    @Override
    public OrderResult addOrderByOffline(SkuOrderAddByDirectReq req) throws BusinessException {
        //查询商户信息
        MerchantQuery param = new MerchantQuery();
        param.setMobile(req.getMobile());
        param.setIsEnable("Y");
        Merchant merchant = merchantDao.findFirst(param);
        if (merchant == null) {
            insertMerchant(req.getMobile());
        }
        merchant = merchantDao.findFirst(param);
        Merchant distributor = merchantDao.findById(req.getPlaceMerchantId());
        isMerchant(req.getMobile(), distributor);
        OrderResult orderResult = new OrderResult();
        List<String> skuNames = new ArrayList<>();
        Sku sku = skuDao.findById(req.getSkuId());
        ValidateBusinessException.assertNonNull(sku, ExceptionEnum.ERROR_1701);
        ValidateBusinessException.assertFalse("N".equals(sku.getIsEnable()), ExceptionEnum.ERROR_1702);
        skuNames.add(sku.getTitle());
        orderResult.setSkuNames(skuNames);
        SkuContent skuContent = skuContentDao.findBySkuId(req.getSkuId());
        ValidateBusinessException.assertNonNull(skuContent, ExceptionEnum.ERROR_1701);
        ValidateBusinessException.assertFalse("Y".equals(req.getIsSpellOrder()) && !"Y".equals(skuContent.getIsSpellOrder()), ExceptionEnum.ERROR_1856);
        SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(req.getSkuSalesInformationId());
        ValidateBusinessException.assertNonNull(skuSalesInformation, ExceptionEnum.ERROR_1703);
        ValidateBusinessException.assertFalse(skuSalesInformation.getStock() < req.getCount(), sku.getTitle() + (ExceptionEnum.ERROR_1816.getMessage()));
        MerchantCity merchantCity = getMerchantCity(req.getMerchantCityId());
        RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(merchantCity.getCityId(), req.getCityId(), req.getSkuSalesInformationId(), sku.getTitle());
        //判断是否参与和拼团人数够
        if (StringUtils.isNotEmpty(req.getPartSn())) {
            SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
            skuOrderQuery.setPartSn(req.getPartSn());
            skuOrderQuery.setMerchantId(merchant.getId());
            skuOrderQuery.setNoStatus(SkuOrderStatusEnum.CANCEL.getCode());
            SkuOrder first = skuOrderDao.findFirst(skuOrderQuery);
            ValidateBusinessException.assertNull(first, ExceptionEnum.ERROR_1860);
            skuOrderQuery = new SkuOrderQuery();
            skuOrderQuery.setPartSn(req.getPartSn());
            skuOrderQuery.setIsApply("N");
            skuOrderQuery.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
            List<SkuOrder> list = skuOrderDao.list(skuOrderQuery);
            if (list == null || list.size() <= 0) {
                throw new BusinessException(ExceptionEnum.ERROR_1851.getCode(), ExceptionEnum.ERROR_1851.getMessage());
            }
            if (list.size() >= skuContent.getSpellOrderPeople()) {
                throw new BusinessException(ExceptionEnum.ERROR_1852.getCode(), ExceptionEnum.ERROR_1852.getMessage());
            }
            skuOrderQuery = new SkuOrderQuery();
            skuOrderQuery.setPartSn(req.getPartSn());
            skuOrderQuery.setIsApply("Y");
            SkuOrder skuOrder = skuOrderDao.findFirst(skuOrderQuery);
            if (skuOrder.getPartFinshTime().before(new Date())) {
                throw new BusinessException(ExceptionEnum.ERROR_1859.getCode(), ExceptionEnum.ERROR_1859.getMessage());
            }
        }
        Order order = new Order();
        order.setMerchantId(merchant.getId());
        order.setOrderType(SkuTypeEnum.SKU.getCode());
        order.setCreateTime(new Date());
        order.setMerchantCityId(req.getMerchantCityId());
        order.setReceiver(merchantCity.getReceiver());
        order.setReceiverMobile(merchantCity.getReceiverMobile());
        order.setSupplierId(sku.getSupplierId());
        order.setAddress(merchantCity.getProvinceName() + merchantCity.getCityName() + merchantCity.getAreaName() + merchantCity.getAddress());
        order.setPlaceMerchantId(req.getPlaceMerchantId());
        orderDao.insert(order);

        //支付价格
        String isRegion = "N";
        Double unitPrice = skuSalesInformation.getPrice();
        Double realityPrice = 0.0;
        SkuOrder skuOrder = new SkuOrder();
        skuOrder.setType(SkuTypeEnum.SKU.getCode());
        Integer count = req.getCount();
        //总价
        double price = skuSalesInformation.getPrice() * count;
        if (regionalSkuSalesInformation != null) {
            price = regionalSkuSalesInformation.getRegionalPrice() * count;
            unitPrice = regionalSkuSalesInformation.getRegionalPrice();
            isRegion = "Y";
        }
        List<SkuRealityPriceReq> skuRealityPriceReqs = req.getSkuRealityPriceReqs();
        if (skuRealityPriceReqs != null && skuRealityPriceReqs.size() > 0) {
            Map<Integer, SkuRealityPriceReq> skuRealityPriceReqMap = skuRealityPriceReqs.stream().collect(Collectors.toMap(SkuRealityPriceReq::getSkuSalesInformationId, i -> i));
            SkuRealityPriceReq skuRealityPriceReq = skuRealityPriceReqMap.get(req.getSkuSalesInformationId());
            if (skuRealityPriceReq != null) {
                price = skuRealityPriceReq.getRealityPrice() * count;
                realityPrice = skuRealityPriceReq.getRealityPrice();
                isRegion = "N";
            }
        }
        //积分价格
        Double integralPrice = 0.0;
        //积分
        Integer integral = 0;

        Double freight = 0.0;
        //计算积分抵扣金额
        if ("Y".equals(skuContent.getIsIntegral()) && "Y".equals(req.getIsUseIntegral())) {
            IntegerPrice integerPrice = getIntegral(req.getIsUseIntegral(), price, merchant, skuContent, skuSalesInformation, regionalSkuSalesInformation);
            integralPrice = integerPrice.getIntegralPrice();
            integral = integerPrice.getIntegral();
            skuOrder.setType(SkuTypeEnum.INTEGRAL.getCode());
        }
        Double payPrice = new BigDecimal(price).subtract(new BigDecimal(integralPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
        payPrice = payPrice > 0 ? payPrice : 0;
        skuOrder.setMerchantId(merchant.getId());
        skuOrder.setOrderId(order.getId());
        skuOrder.setTotalPrice(price);
        skuOrder.setPayPrice(payPrice);
        skuOrder.setIntegralPrice(integralPrice);
        skuOrder.setIntegral(integral);
        skuOrder.setStatus(SkuOrderStatusEnum.PAY.getCode());
        skuOrder.setSupplierId(sku.getSupplierId());
        skuOrder.setBuyWay(SkuOrderBuyTypeEnum.DIRECT.getCode());
        skuOrder.setOrderType(SkuOrderTypeEnum.OFFLINE.getCode());
        skuOrder.setIsRegion(isRegion);
        //拼团商品操作
        if ("Y".equals(req.getIsSpellOrder()) && "Y".equals(skuContent.getIsSpellOrder())) {
            if (!merchantCity.getProvinceId().equals(skuContent.getSpellOrderProvinceId()) || !merchantCity.getCityId().equals(skuContent.getSpellOrderCityId())) {
                throw new BusinessException(ExceptionEnum.ERROR_1857.getCode(), ExceptionEnum.ERROR_1857.getMessage());
            }
            PlatformSystemDeployQuery secondPlatformSystemDeployQuery = new PlatformSystemDeployQuery();
            secondPlatformSystemDeployQuery.setType(SkuTypeEnum.PART.getCode());
            secondPlatformSystemDeployQuery.setStatus("finishTime");
            PlatformSystemDeploy secondPlatformSystemDeploy = platformSystemDeployDao.findFirst(secondPlatformSystemDeployQuery);
            ValidateBusinessException.assertNonNull(secondPlatformSystemDeploy, ExceptionEnum.ERROR_1705);
            skuOrder.setType(SkuTypeEnum.PART.getCode());
            if (StringUtils.isNotEmpty(req.getPartSn())) {
                skuOrder.setPartSn(req.getPartSn());
                skuOrder.setIsSponsor("N");
            } else {
                skuOrder.setPartSn(UUIDUtils.getUUID());
                skuOrder.setIsSponsor("Y");
            }
            skuOrder.setPartStatus(SkuOrderStatusEnum.WAITING.getCode());
            skuOrder.setPartFinshTime(getWebExpireTime(secondPlatformSystemDeploy.getUnit(), secondPlatformSystemDeploy.getDetails().intValue(), order.getCreateTime()));
        }
        skuOrder.setAppletType(req.getAppletType());
        skuOrderDao.insert(skuOrder);
        SkuOrderDetail skuOrderDetail = new SkuOrderDetail();
        skuOrderDetail.setMerchantId(merchant.getId());
        skuOrderDetail.setSkuOrderId(skuOrder.getId());
        skuOrderDetail.setSkuId(req.getSkuId());
        skuOrderDetail.setSkuSalesInformationId(req.getSkuSalesInformationId());
        skuOrderDetail.setSupplierId(sku.getSupplierId());
        skuOrderDetail.setPrice(unitPrice);
        skuOrderDetail.setPayPrice(payPrice);
        skuOrderDetail.setCount(req.getCount());
        skuOrderDetail.setDeliveryWay(skuContent.getLogistics());
        skuOrderDetail.setIntegral(integral);
        skuOrderDetail.setIsRegion(isRegion);
        skuOrderDetail.setRealityPrice(realityPrice);
        skuOrderDetailDao.insert(skuOrderDetail);
        if (skuContent.getLogistics().equals(DeliveryWayEnum.FULLREDUCTION.getCode())) {
            UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
            urbanFullReductionQuery.setCityId(req.getCityId());
            UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            if (urbanFullReductionDaoFirst == null) {
                urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            }
            if (payPrice < urbanFullReductionDaoFirst.getMoney()) {
                SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
                skuOrderDeliveryDemand.setSkuOrderId(skuOrder.getId());
                skuOrderDeliveryDemand.setMerchantId(merchant.getId());
                skuOrderDeliveryDemand.setPostage(urbanFullReductionDaoFirst.getFreight());
                skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.WAITING.getCode());
                skuOrderDeliveryDemand.setCreateTime(new Date());
                skuOrderDeliveryDemand.setLogistics(skuContent.getLogistics());
                skuOrderDeliveryDemandDao.insert(skuOrderDeliveryDemand);
                SkuOrderDetail updateSkuOrder = new SkuOrderDetail();
                updateSkuOrder.setId(skuOrderDetail.getId());
                updateSkuOrder.setIsHavingPostage("Y");
                skuOrderDetailDao.updateById(updateSkuOrder);
                freight = urbanFullReductionDaoFirst.getFreight();
            } else {
                SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
                skuOrderDeliveryDemand.setSkuOrderId(skuOrder.getId());
                skuOrderDeliveryDemand.setMerchantId(merchant.getId());
                skuOrderDeliveryDemand.setPostage(0.0);
                skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.PAY.getCode());
                skuOrderDeliveryDemand.setPostagePayTime(new Date());
                skuOrderDeliveryDemand.setCreateTime(new Date());
                skuOrderDeliveryDemand.setLogistics(skuContent.getLogistics());
                skuOrderDeliveryDemandDao.insert(skuOrderDeliveryDemand);
                SkuOrderDetail updateSkuOrder = new SkuOrderDetail();
                updateSkuOrder.setId(skuOrderDetail.getId());
                updateSkuOrder.setIsHavingPostage("Y");
                skuOrderDetailDao.updateById(updateSkuOrder);
            }
        }

        Order order1 = new Order();
        order1.setId(order.getId());
        order1.setTotalPrice(price > 0 ? price : 0);
        order1.setPayPrice(payPrice > 0 ? payPrice : 0);
        orderDao.updateById(order1);
        Order newOrder = orderDao.findById(order.getId());
        BeanUtils.copyProperties(orderResult, newOrder);
        orderResult.setTotalPrice(price + freight);
        orderResult.setPayPrice(payPrice + freight);
        orderResult.setOutOrderId(environment + OrderTypeEnum.SKU.getCode() + "-" + skuOrder.getId());
        Double finalPayPrice = payPrice;
        double finalPrice = price;
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Integer fengyongMerchantId = null;
                    Double fengyongProportion = 0.0;
                    Double fengxiaoProportion = null;
                    DailiMerchantQuery param = new DailiMerchantQuery();
                    param.setMobile(distributor.getMobile());
                    param.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
                    param.setIsEnable("Y");
                    DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(param);
                    if (dailiMerchant == null) {
                        throw BusinessException.build(ExceptionEnum.ERROR_1902);
                    }
                    if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(dailiMerchant.getRole())) {
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        fengxiaoProportion = dailiMerchant.getProportion();
                        fengyongMerchantId = dailiMerchant.getPid();
                    } else if (DailiMerchantRoleEnum.MERCHANT.getCode().equals(dailiMerchant.getRole())) {
                        fengyongMerchantId = Integer.parseInt(dailiMerchant.getPidPath().split(",")[0]);
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(secondMerchant.getRole())) {
                            DailiMerchant thirdMerchant = dailiMerchantDao.findById(secondMerchant.getPid());
                            if (!"Y".equals(thirdMerchant.getIsEnable())) {
                                throw BusinessException.build(ExceptionEnum.ERROR_1902);
                            }
                            fengxiaoProportion = secondMerchant.getProportion();
                        }
                    } else {
                        fengyongMerchantId = dailiMerchant.getId();
                    }
                    DailiMerchantSkuQuery dailiMerchantSkuQuery = new DailiMerchantSkuQuery();
                    dailiMerchantSkuQuery.setDailiMerchantId(fengyongMerchantId);
                    dailiMerchantSkuQuery.setSkuId(req.getSkuId());
                    DailiMerchantSku dailiMerchantSku = dailiMerchantSkuDao.findFirst(dailiMerchantSkuQuery);
                    if (dailiMerchantSku == null) {
                        throw BusinessException.build(ExceptionEnum.ERROR_1903);
                    }
                    fengyongProportion = dailiMerchantSku.getProportion();
                    if (regionalSkuSalesInformation != null && regionalSkuSalesInformation.getProportion() != null) {
                        fengyongProportion = regionalSkuSalesInformation.getProportion();
                    }
                    DailiOrder dailiOrder = new DailiOrder();
                    dailiOrder.setOrderId(skuOrderDetail.getId());
                    dailiOrder.setDailiMerchantId(dailiMerchant.getId());
                    dailiOrder.setDailiPidPath(dailiMerchant.getPidPath());
                    dailiOrder.setSkuId(req.getSkuId());
                    dailiOrder.setOrderAmount(finalPrice);
                    dailiOrder.setPayAmount(finalPayPrice);
                    double fengyongAmount = new BigDecimal(finalPayPrice + "").multiply(new BigDecimal(fengyongProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                    dailiOrder.setFengyongAmount(fengyongAmount);
                    if (fengxiaoProportion != null) {
                        double fenxiaoyuanAmount = new BigDecimal(fengyongAmount + "").multiply(new BigDecimal(fengxiaoProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                        dailiOrder.setFengxiaoyuanAmount(fenxiaoyuanAmount);
                        dailiOrder.setFengyongAmount(new BigDecimal(fengyongAmount + "").subtract(new BigDecimal(fenxiaoyuanAmount + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
                    }
                    dailiOrder.setCreateTime(new Date());
                    dailiOrder.setDate(DateUtil.date(new Date(), "yyyy-MM"));
                    dailiOrderDao.insert(dailiOrder);
                } catch (BusinessException e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                }
            }
        });
        return orderResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addOrderByEnjoy(SkuOrderAddByDirectReq req) throws BusinessException {
        Merchant merchant = merchantDao.findById(req.getMerchantId());
        DailiMerchantQuery dailiMerchantQuery = new DailiMerchantQuery();
        dailiMerchantQuery.setMobile(merchant.getMobile());
        dailiMerchantQuery.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
        dailiMerchantQuery.setIsEnable("Y");
        dailiMerchantQuery.setRole(DailiMerchantRoleEnum.MERCHANT.getCode());
        DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(dailiMerchantQuery);
        if (dailiMerchant == null) {
            throw BusinessException.build(ExceptionEnum.ERROR_1869);
        }
        if (dailiMerchant.getQuota() == null || dailiMerchant.getQuota() == 0) {
            throw BusinessException.build(ExceptionEnum.ERROR_1869);
        }
        Double enjoyPayPrice = skuOrderDao.getEnjoyPayPrice(req.getMerchantId(), null, null);
        DailiMerchant partnerMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
        if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(partnerMerchant.getRole())) {
            partnerMerchant = dailiMerchantDao.findById(partnerMerchant.getPid());
        }
        DailiMerchantQuery partnerMerchantQuery = new DailiMerchantQuery();
        partnerMerchantQuery.setPidPath(partnerMerchant.getPidPath());
        partnerMerchantQuery.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
        partnerMerchantQuery.setIsEnable("Y");
        partnerMerchantQuery.setRole(DailiMerchantRoleEnum.MERCHANT.getCode());
        partnerMerchantQuery.setNoQuota(0.0);
        List<DailiMerchant> dailiMerchants = dailiMerchantDao.list(partnerMerchantQuery);
        List<String> mobileList = dailiMerchants.stream().map(DailiMerchant::getMobile).collect(Collectors.toList());
        List<Integer> merchantList = merchantDao.findByMobiles(mobileList).stream().map(Merchant::getId).collect(Collectors.toList());
        Double enjoyPayPriceByMerchantIds = skuOrderDao.getEnjoyPayPriceByMerchantIds(merchantList, null, null);
        Sku sku = skuDao.findById(req.getSkuId());
        ValidateBusinessException.assertNonNull(sku, ExceptionEnum.ERROR_1701);
        ValidateBusinessException.assertFalse("N".equals(sku.getIsEnable()), ExceptionEnum.ERROR_1702);
        SkuContent skuContent = skuContentDao.findBySkuId(req.getSkuId());
        ValidateBusinessException.assertNonNull(skuContent, ExceptionEnum.ERROR_1701);
        ValidateBusinessException.assertFalse("Y".equals(req.getIsSpellOrder()) && !"Y".equals(skuContent.getIsSpellOrder()), ExceptionEnum.ERROR_1856);
        SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(req.getSkuSalesInformationId());
        ValidateBusinessException.assertNonNull(skuSalesInformation, ExceptionEnum.ERROR_1703);
        ValidateBusinessException.assertFalse(skuSalesInformation.getStock() < req.getCount(), sku.getTitle() + (ExceptionEnum.ERROR_1816.getMessage()));
        MerchantCity merchantCity = getMerchantCity(req.getMerchantCityId());
        RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(merchantCity.getCityId(), req.getCityId(), req.getSkuSalesInformationId(), sku.getTitle());
        if (req.getCityId() != null) {
            RegionalSku regionalSku = regionalSkuDao.findBySkuId(req.getSkuId());
            if (regionalSku != null) {
                if ("N".equals(req.getIsByBalance()) && "Y".equals(regionalSku.getIsMembersExclusive())) {
                    throw new BusinessException(ExceptionEnum.ERROR_1713.getCode(), sku.getTitle() + "," + ExceptionEnum.ERROR_1713.getMessage());
                }
            }
        }
        EnjoyBeforePaySkuQuery enjoyBeforePaySkuQuery = new EnjoyBeforePaySkuQuery();
        enjoyBeforePaySkuQuery.setSkuId(sku.getId());
        EnjoyBeforePaySku enjoyBeforePaySku = enjoyBeforePaySkuDao.findFirst(enjoyBeforePaySkuQuery);
        ValidateBusinessException.assertNonNull(enjoyBeforePaySku, ExceptionEnum.ERROR_1709);
        //判断是否参与和拼团人数够
        if (StringUtils.isNotEmpty(req.getPartSn())) {
            SkuOrderQuery param = new SkuOrderQuery();
            param.setPartSn(req.getPartSn());
            param.setMerchantId(req.getMerchantId());
            param.setNoStatus(SkuOrderStatusEnum.CANCEL.getCode());
            SkuOrder first = skuOrderDao.findFirst(param);
            ValidateBusinessException.assertNull(first, ExceptionEnum.ERROR_1860);
            param = new SkuOrderQuery();
            param.setPartSn(req.getPartSn());
            param.setIsApply("N");
            param.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
            List<SkuOrder> list = skuOrderDao.list(param);
            if (list == null || list.size() <= 0) {
                throw new BusinessException(ExceptionEnum.ERROR_1851.getCode(), ExceptionEnum.ERROR_1851.getMessage());
            }
            if (list.size() >= skuContent.getSpellOrderPeople()) {
                throw new BusinessException(ExceptionEnum.ERROR_1852.getCode(), ExceptionEnum.ERROR_1852.getMessage());
            }
            param = new SkuOrderQuery();
            param.setPartSn(req.getPartSn());
            param.setIsApply("Y");
            SkuOrder skuOrder = skuOrderDao.findFirst(param);
            if (skuOrder.getPartFinshTime().before(new Date())) {
                throw new BusinessException(ExceptionEnum.ERROR_1859.getCode(), ExceptionEnum.ERROR_1859.getMessage());
            }
        }

        Order order = new Order();
        order.setMerchantId(req.getMerchantId());
        order.setOrderType(SkuTypeEnum.SKU.getCode());
        order.setCreateTime(new Date());
        order.setMerchantCityId(req.getMerchantCityId());
        order.setReceiver(merchantCity.getReceiver());
        order.setReceiverMobile(merchantCity.getReceiverMobile());
        order.setSupplierId(sku.getSupplierId());
        order.setAddress(merchantCity.getProvinceName() + merchantCity.getCityName() + merchantCity.getAreaName() + merchantCity.getAddress());
        orderDao.insert(order);
        //支付价格
        Double totalPayPrice = 0.0;
        Double unitPrice = skuSalesInformation.getPrice();
        SkuOrder skuOrder = new SkuOrder();
        skuOrder.setType(SkuTypeEnum.SKU.getCode());
        Integer count = req.getCount();
        String isRegion = "N";
        //总价
        double price = skuSalesInformation.getPrice() * count;
        //计算区域价格
        if (regionalSkuSalesInformation != null) {
            price = regionalSkuSalesInformation.getRegionalPrice() * count;
            unitPrice = regionalSkuSalesInformation.getRegionalPrice();
            isRegion = "Y";
        }
        if ("Y".equals(req.getIsSpellOrder())) {
            price = skuSalesInformation.getSpellOrderPrice() * count;
        }
        //计算积分抵扣金额
        IntegerPrice ip = getIntegral(req.getIsUseIntegral(), price, merchant, skuContent, skuSalesInformation, regionalSkuSalesInformation);
        //积分价格
        Double integralPrice = ip.getIntegralPrice();
        //积分
        Integer integral = ip.getIntegral();
        Double payPrice = new BigDecimal(price).subtract(new BigDecimal(integralPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
        payPrice = payPrice > 0 ? payPrice : 0;
        totalPayPrice += payPrice;
        skuOrder.setMerchantId(req.getMerchantId());
        skuOrder.setOrderId(order.getId());
        skuOrder.setTotalPrice(price);
        skuOrder.setPayPrice(payPrice);
        skuOrder.setIntegralPrice(integralPrice);
        skuOrder.setIntegral(integral);
        skuOrder.setStatus(SkuOrderStatusEnum.PAY.getCode());
        skuOrder.setSupplierId(sku.getSupplierId());
        skuOrder.setBuyWay(SkuOrderBuyTypeEnum.DIRECT.getCode());
        skuOrder.setOrderType(SkuOrderTypeEnum.ENJOY.getCode());
        //拼团商品操作
        if ("Y".equals(req.getIsSpellOrder()) && "Y".equals(skuContent.getIsSpellOrder())) {
            if (!merchantCity.getProvinceId().equals(skuContent.getSpellOrderProvinceId()) || !merchantCity.getCityId().equals(skuContent.getSpellOrderCityId())) {
                throw new BusinessException(ExceptionEnum.ERROR_1857.getCode(), ExceptionEnum.ERROR_1857.getMessage());
            }
            PlatformSystemDeployQuery secondPlatformSystemDeployQuery = new PlatformSystemDeployQuery();
            secondPlatformSystemDeployQuery.setType(SkuTypeEnum.PART.getCode());
            secondPlatformSystemDeployQuery.setStatus("finishTime");
            PlatformSystemDeploy secondPlatformSystemDeploy = platformSystemDeployDao.findFirst(secondPlatformSystemDeployQuery);
            ValidateBusinessException.assertNonNull(secondPlatformSystemDeploy, ExceptionEnum.ERROR_1705);
            skuOrder.setType(SkuTypeEnum.PART.getCode());
            if (StringUtils.isNotEmpty(req.getPartSn())) {
                skuOrder.setPartSn(req.getPartSn());
                skuOrder.setIsSponsor("N");
            } else {
                skuOrder.setPartSn(UUIDUtils.getUUID());
                skuOrder.setIsSponsor("Y");
            }
            skuOrder.setPartStatus(SkuOrderStatusEnum.WAITING.getCode());
            skuOrder.setPartFinshTime(getWebExpireTime(secondPlatformSystemDeploy.getUnit(), secondPlatformSystemDeploy.getDetails().intValue(), order.getCreateTime()));
        }
        skuOrder.setAppletType(req.getAppletType());
        skuOrderDao.insert(skuOrder);
        SkuOrderDetail skuOrderDetail = new SkuOrderDetail();
        skuOrderDetail.setMerchantId(req.getMerchantId());
        skuOrderDetail.setSkuOrderId(skuOrder.getId());
        skuOrderDetail.setSkuId(req.getSkuId());
        skuOrderDetail.setSkuSalesInformationId(req.getSkuSalesInformationId());
        skuOrderDetail.setSupplierId(sku.getSupplierId());
        skuOrderDetail.setPrice(unitPrice);
        skuOrderDetail.setPayPrice(payPrice);
        skuOrderDetail.setCount(req.getCount());
        skuOrderDetail.setDeliveryWay(skuContent.getLogistics());
        skuOrderDetail.setIntegral(integral);
        skuOrderDetail.setIsRegion(isRegion);
        skuOrderDetailDao.insert(skuOrderDetail);
        Integer integer = skuSalesInformationDao.deleteStock(skuOrderDetail.getSkuSalesInformationId(), skuOrderDetail.getCount());
        ValidateBusinessException.assertTrue(integer > 0, ExceptionEnum.ERROR_1826.getCode(), skuOrderDetail.getSkuSalesInformationId() + "," + ExceptionEnum.ERROR_1826.getMessage());
        if (StringUtils.isNotEmpty(skuOrder.getPartSn())) {
            SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
            skuOrderQuery.setPartSn(skuOrder.getPartSn());
            skuOrderQuery.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
            List<SkuOrder> list = skuOrderDao.list(skuOrderQuery);
            if (list.size() >= skuContent.getSpellOrderPeople()) {
                skuOrderDao.updateByPartSn(skuOrder.getPartSn());
            }
        }
        if (skuOrder.getIntegral() > 0) {
            Merchant before = merchantDao.findById(skuOrder.getMerchantId());
            Integer integer1 = merchantDao.deleteIntegral(skuOrder.getMerchantId(), skuOrder.getIntegral());
            Merchant after = merchantDao.findById(skuOrder.getMerchantId());
            ValidateBusinessException.assertTrue(integer1 > 0, ExceptionEnum.ERROR_1827.getCode(), skuOrder.getId() + "," + ExceptionEnum.ERROR_1827.getMessage());
            MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
            merchantIntegralLog.setMerchantId(skuOrder.getMerchantId());
            merchantIntegralLog.setOperation(IntegralOperationEnum.DEDUCTION.getCode());
            merchantIntegralLog.setBeforeIntegral(before.getIntegral());
            merchantIntegralLog.setAfterIntegral(after.getIntegral());
            merchantIntegralLog.setCreateTime(new Date());
            merchantIntegralLogDao.insert(merchantIntegralLog);
        }
        if (skuContent.getLogistics().equals(DeliveryWayEnum.FULLREDUCTION.getCode())) {
            UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
            urbanFullReductionQuery.setCityId(req.getCityId());
            UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            if (urbanFullReductionDaoFirst == null) {
                urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            }
            if (payPrice < urbanFullReductionDaoFirst.getMoney()) {
                SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
                skuOrderDeliveryDemand.setSkuOrderId(skuOrder.getId());
                skuOrderDeliveryDemand.setMerchantId(merchant.getId());
                skuOrderDeliveryDemand.setPostage(urbanFullReductionDaoFirst.getFreight());
                skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.WAITING.getCode());
                skuOrderDeliveryDemand.setCreateTime(new Date());
                skuOrderDeliveryDemand.setLogistics(skuContent.getLogistics());
                skuOrderDeliveryDemandDao.insert(skuOrderDeliveryDemand);
                SkuOrderDetail updateSkuOrder = new SkuOrderDetail();
                updateSkuOrder.setId(skuOrderDetail.getId());
                updateSkuOrder.setIsHavingPostage("Y");
                skuOrderDetailDao.updateById(updateSkuOrder);
                payPrice = payPrice + urbanFullReductionDaoFirst.getFreight();
                price = price + urbanFullReductionDaoFirst.getFreight();
            } else {
                SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
                skuOrderDeliveryDemand.setSkuOrderId(skuOrder.getId());
                skuOrderDeliveryDemand.setMerchantId(merchant.getId());
                skuOrderDeliveryDemand.setPostage(0.0);
                skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.PAY.getCode());
                skuOrderDeliveryDemand.setPostagePayTime(new Date());
                skuOrderDeliveryDemand.setCreateTime(new Date());
                skuOrderDeliveryDemand.setLogistics(skuContent.getLogistics());
                skuOrderDeliveryDemandDao.insert(skuOrderDeliveryDemand);
                SkuOrderDetail updateSkuOrder = new SkuOrderDetail();
                updateSkuOrder.setId(skuOrderDetail.getId());
                updateSkuOrder.setIsHavingPostage("Y");
                skuOrderDetailDao.updateById(updateSkuOrder);
            }
        }
        Order param = new Order();
        param.setId(order.getId());
        param.setTotalPrice(price > 0 ? price : 0);
        param.setPayPrice(totalPayPrice > 0 ? totalPayPrice : 0);
        orderDao.updateById(param);
        if (enjoyPayPrice + payPrice > dailiMerchant.getQuota()) {
            throw BusinessException.build(ExceptionEnum.ERROR_1870);
        }
        if (enjoyPayPriceByMerchantIds + payPrice > partnerMerchant.getQuota()) {
            throw BusinessException.build(ExceptionEnum.ERROR_1871);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderResult addOrderCarByEnjoy(SkuOrderAddReq req) throws BusinessException {
        Merchant merchant = merchantDao.findById(req.getMerchantId());
        DailiMerchantQuery dailiMerchantQuery = new DailiMerchantQuery();
        dailiMerchantQuery.setMobile(merchant.getMobile());
        dailiMerchantQuery.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
        dailiMerchantQuery.setIsEnable("Y");
        dailiMerchantQuery.setRole(DailiMerchantRoleEnum.MERCHANT.getCode());
        DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(dailiMerchantQuery);
        if (dailiMerchant == null) {
            throw BusinessException.build(ExceptionEnum.ERROR_1869);
        }
        if (dailiMerchant.getQuota() == null || dailiMerchant.getQuota() == 0) {
            throw BusinessException.build(ExceptionEnum.ERROR_1869);
        }
        Double enjoyPayPrice = skuOrderDao.getEnjoyPayPrice(req.getMerchantId(), null, null);
        DailiMerchant partnerMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
        if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(partnerMerchant.getRole())) {
            partnerMerchant = dailiMerchantDao.findById(partnerMerchant.getPid());
        }
        DailiMerchantQuery partnerMerchantQuery = new DailiMerchantQuery();
        partnerMerchantQuery.setPidPath(partnerMerchant.getPidPath());
        partnerMerchantQuery.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
        partnerMerchantQuery.setIsEnable("Y");
        partnerMerchantQuery.setRole(DailiMerchantRoleEnum.MERCHANT.getCode());
        partnerMerchantQuery.setNoQuota(0.0);
        List<DailiMerchant> dailiMerchants = dailiMerchantDao.list(partnerMerchantQuery);
        List<String> mobileList = dailiMerchants.stream().map(DailiMerchant::getMobile).collect(Collectors.toList());
        List<Integer> merchantList = merchantDao.findByMobiles(mobileList).stream().map(Merchant::getId).collect(Collectors.toList());
        Double enjoyPayPriceByMerchantIds = skuOrderDao.getEnjoyPayPriceByMerchantIds(merchantList, null, null);
        OrderResult orderResult = new OrderResult();
        List<String> skuNames = new ArrayList<>();
        PlatformSystemDeploy platformSystemDeploy = jfPlatformSystemDeploy();
        MerchantCity merchantCity = getMerchantCity(req.getMerchantCityId());
        Order order = new Order();
        order.setMerchantId(req.getMerchantId());
        order.setOrderType(SkuTypeEnum.SKU.getCode());
        order.setCreateTime(new Date());
        order.setMerchantCityId(req.getMerchantCityId());
        order.setReceiver(merchantCity.getReceiver());
        order.setReceiverMobile(merchantCity.getReceiverMobile());
        order.setAddress(merchantCity.getProvinceName() + merchantCity.getCityName() + merchantCity.getAreaName() + merchantCity.getAddress());
        orderDao.insert(order);
        //总价
        Double totalPrice = 0.0;
        //支付价格
        Double totalPayPrice = 0.0;
        //积分价格
        Double integerPrice = 0.0;
        //积分
        Integer integralPrice = 0;
        //积分
        Double unitPrice = 0.0;
        //商户积分
        Integer merchantIntegral = merchant.getIntegral();
        //
        Double fullReductionPrice = 0.0;
        List<SkuOrderDetail> skuOrderDetails = new ArrayList<>();
        List<SkuShopcar> skuShopcars = skuShopcarDao.findByIds(req.getSkuShopcarId());
        for (SkuShopcar skuShopcar : skuShopcars) {
            SkuOrderDetail skuOrderDetail = new SkuOrderDetail();
            ValidateBusinessException.assertTrue(req.getMerchantId().equals(skuShopcar.getMerchantId()), ExceptionEnum.ERROR_1853);
            Integer count = skuShopcar.getCount();
            Sku sku = skuDao.findById(skuShopcar.getSkuId());
            ValidateBusinessException.assertNonNull(sku, ExceptionEnum.ERROR_1701);
            ValidateBusinessException.assertFalse("N".equals(sku.getIsEnable()), ExceptionEnum.ERROR_1702);
            skuNames.add(sku.getTitle());
            SkuContent skuContent = skuContentDao.findBySkuId(skuShopcar.getSkuId());
            ValidateBusinessException.assertNonNull(skuContent, ExceptionEnum.ERROR_1701);
            SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuShopcar.getSkuSalesInformationId());
            ValidateBusinessException.assertNonNull(skuSalesInformation, ExceptionEnum.ERROR_1703);
            ValidateBusinessException.assertFalse(skuSalesInformation.getStock() < skuShopcar.getCount(), ExceptionEnum.ERROR_1816.getCode(), sku.getTitle() + (ExceptionEnum.ERROR_1816.getMessage()));
            EnjoyBeforePaySkuQuery enjoyBeforePaySkuQuery = new EnjoyBeforePaySkuQuery();
            enjoyBeforePaySkuQuery.setSkuId(sku.getId());
            EnjoyBeforePaySku enjoyBeforePaySku = enjoyBeforePaySkuDao.findFirst(enjoyBeforePaySkuQuery);
            if (enjoyBeforePaySku == null) {
                continue;
            }
            Double price = new BigDecimal(skuSalesInformation.getPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            unitPrice = skuSalesInformation.getPrice();
            RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(merchantCity.getCityId(), req.getCityId(), skuShopcar.getSkuSalesInformationId(), sku.getTitle());
            if (regionalSkuSalesInformation != null) {
                price = new BigDecimal(regionalSkuSalesInformation.getRegionalPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                unitPrice = regionalSkuSalesInformation.getRegionalPrice();
                skuOrderDetail.setIsRegion("Y");
            }
            totalPrice += price;
            IntegerPrice ip = getIntegral(req.getIsUseIntegral(), price, merchant, skuContent, skuSalesInformation, regionalSkuSalesInformation);
            integralPrice = ip.getIntegral();
            integerPrice = ip.getIntegralPrice();
            //商户扣减积分
            merchantIntegral -= integralPrice;
            double payPrice = 0.0;
            if (price >= integerPrice) {
                payPrice = new BigDecimal(price).subtract(new BigDecimal(integerPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            }
            totalPayPrice += payPrice;
            ValidateBusinessException.assertFalse("Y".equals(skuContent.getIsSpellOrder()), ExceptionEnum.ERROR_1707);
            if (skuContent.getLogistics().equals(DeliveryWayEnum.FULLREDUCTION.getCode())) {
                fullReductionPrice += payPrice;
            }
            skuOrderDetail.setSkuId(skuShopcar.getSkuId());
            skuOrderDetail.setSkuSalesInformationId(skuShopcar.getSkuSalesInformationId());
            skuOrderDetail.setSupplierId(sku.getSupplierId());
            skuOrderDetail.setPrice(unitPrice);
            skuOrderDetail.setCount(skuShopcar.getCount());
            skuOrderDetail.setDeliveryWay(skuContent.getLogistics());
            skuOrderDetail.setTotalPrice(price);
            skuOrderDetail.setPayPrice(payPrice);
            skuOrderDetail.setTotalInteger(integralPrice);
            skuOrderDetail.setIntegral(integralPrice);
            skuOrderDetail.setMerchantId(req.getMerchantId());
            skuOrderDetails.add(skuOrderDetail);
        }
        Boolean isHavingPostage = false;
        Double freight = 0.0;
        if (fullReductionPrice > 0.0) {
            UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
            urbanFullReductionQuery.setCityId(req.getCityId());
            UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            if (urbanFullReductionDaoFirst == null) {
                urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            }
            if (fullReductionPrice < urbanFullReductionDaoFirst.getMoney()) {
                isHavingPostage = true;
                freight = urbanFullReductionDaoFirst.getFreight();
            }
        }
        Order param = new Order();
        param.setId(order.getId());
        param.setTotalPrice(totalPrice);
        param.setPayPrice(totalPayPrice);
        orderDao.updateById(param);
        Order newOrder = orderDao.findById(order.getId());
        BeanUtils.copyProperties(orderResult, newOrder);
        orderResult.setTotalPrice(totalPrice + freight);
        orderResult.setPayPrice(totalPayPrice + freight);
        List<SkuOrderDetail> skuOrderDetailsList = addSkuOrderByCar(req.getAppletType(), SkuOrderTypeEnum.ENJOY, skuOrderDetails,
                order.getId(), req.getMerchantId(), freight, isHavingPostage, req.getCityId());
        orderResult.setOutOrderId(environment + OrderTypeEnum.CAR.getCode() + "-" + newOrder.getId());
        orderResult.setSkuNames(skuNames);
        skuShopcarDao.deleteByIds(req.getSkuShopcarId(), req.getMerchantId());
        if (enjoyPayPrice + totalPayPrice > dailiMerchant.getQuota()) {
            throw BusinessException.build(ExceptionEnum.ERROR_1870);
        }
        if (enjoyPayPriceByMerchantIds + totalPayPrice > partnerMerchant.getQuota()) {
            throw BusinessException.build(ExceptionEnum.ERROR_1871);
        }
        //添加分佣信息
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Integer fengyongMerchantId = null;
                    Double fengyongProportion = 0.0;
                    Double fengxiaoProportion = null;
                    DailiMerchantQuery param = new DailiMerchantQuery();
                    param.setMobile(merchant.getMobile());
                    param.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
                    param.setIsEnable("Y");
                    DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(param);
                    if (dailiMerchant == null) {
                        throw BusinessException.build(ExceptionEnum.ERROR_1902);
                    }
                    if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(dailiMerchant.getRole())) {
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        fengxiaoProportion = dailiMerchant.getProportion();
                        fengyongMerchantId = dailiMerchant.getPid();
                    } else if (DailiMerchantRoleEnum.MERCHANT.getCode().equals(dailiMerchant.getRole())) {
                        fengyongMerchantId = Integer.parseInt(dailiMerchant.getPidPath().split(",")[0]);
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(secondMerchant.getRole())) {
                            DailiMerchant thirdMerchant = dailiMerchantDao.findById(secondMerchant.getPid());
                            if (!"Y".equals(thirdMerchant.getIsEnable())) {
                                throw BusinessException.build(ExceptionEnum.ERROR_1902);
                            }
                            fengxiaoProportion = secondMerchant.getProportion();
                        }
                    } else {
                        fengyongMerchantId = dailiMerchant.getId();
                    }
                    for (SkuOrderDetail skuOrderDetail : skuOrderDetailsList) {
                        DailiMerchantSkuQuery dailiMerchantSkuQuery = new DailiMerchantSkuQuery();
                        dailiMerchantSkuQuery.setDailiMerchantId(fengyongMerchantId);
                        dailiMerchantSkuQuery.setSkuId(skuOrderDetail.getSkuId());
                        DailiMerchantSku dailiMerchantSku = dailiMerchantSkuDao.findFirst(dailiMerchantSkuQuery);
                        if (dailiMerchantSku != null) {
                            fengyongProportion = dailiMerchantSku.getProportion();
                            RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(merchantCity.getCityId(), req.getCityId(), skuOrderDetail.getSkuSalesInformationId(), dailiMerchantSku.getTitle());
                            if (regionalSkuSalesInformation != null && regionalSkuSalesInformation.getProportion() != null) {
                                fengyongProportion = regionalSkuSalesInformation.getProportion();

                            }
                            DailiOrder dailiOrder = new DailiOrder();
                            dailiOrder.setOrderId(skuOrderDetail.getId());
                            dailiOrder.setDailiMerchantId(dailiMerchant.getId());
                            dailiOrder.setDailiPidPath(dailiMerchant.getPidPath());
                            dailiOrder.setSkuId(skuOrderDetail.getSkuId());
                            dailiOrder.setOrderAmount(skuOrderDetail.getPrice());
                            dailiOrder.setPayAmount(skuOrderDetail.getPayPrice());
                            double fengyongAmount = new BigDecimal(skuOrderDetail.getPayPrice() + "").multiply(new BigDecimal(fengyongProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                            dailiOrder.setFengyongAmount(fengyongAmount);
                            if (fengxiaoProportion != null) {
                                double fenxiaoyuanAmount = new BigDecimal(fengyongAmount + "").multiply(new BigDecimal(fengxiaoProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                                dailiOrder.setFengxiaoyuanAmount(fenxiaoyuanAmount);
                                dailiOrder.setFengyongAmount(new BigDecimal(fengyongAmount + "").subtract(new BigDecimal(fenxiaoyuanAmount + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
                            }
                            dailiOrder.setCreateTime(new Date());
                            dailiOrder.setDate(DateUtil.date(new Date(), "yyyy-MM"));
                            dailiOrderDao.insert(dailiOrder);
                        }
                    }
                } catch (BusinessException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return orderResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderResult addPeriodizationDepositOrder(PeriodizationDepositOrderReq req) throws BusinessException {
        OrderResult orderResult = new OrderResult();
        String isRegion = "N";
        Integer supplierId = null;
        List<PeriodizationSkuListReq> periodizationSkuListReqs = req.getPeriodizationSkuListReqs();
        MerchantCity merchantCity = getMerchantCity(req.getMerchantCityId());
        Order insertOrder = new Order();
        insertOrder.setMerchantId(req.getMerchantId());
        insertOrder.setOrderType(SkuTypeEnum.SKU.getCode());
        insertOrder.setCreateTime(new Date());
        insertOrder.setMerchantCityId(req.getMerchantCityId());
        insertOrder.setReceiver(merchantCity.getReceiver());
        insertOrder.setReceiverMobile(merchantCity.getReceiverMobile());
        insertOrder.setAddress(merchantCity.getProvinceName() + merchantCity.getCityName() + merchantCity.getAreaName() + merchantCity.getAddress());
        insertOrder.setPeriodsNumber(req.getPeriodsNumber());
        insertOrder.setRemindDate(req.getRemindDate());
        insertOrder.setType(SkuSalesInformationTypeEnum.PERIODIZATION.getCode());
        insertOrder.setPeriodsNumber(req.getPeriodsNumber());
        orderDao.insert(insertOrder);
        //支付价格
        Double totalPrice = 0.0;
        Double totalPayPrice = 0.0;
        SkuOrder inserSkuOrder = new SkuOrder();
        inserSkuOrder.setOrderId(insertOrder.getId());
        inserSkuOrder.setMerchantId(req.getMerchantId());
        inserSkuOrder.setTotalPrice(totalPrice);
        inserSkuOrder.setPayPrice(totalPrice);
        inserSkuOrder.setIntegralPrice(totalPrice);
        inserSkuOrder.setIntegral(0);
        inserSkuOrder.setStatus(SkuOrderStatusEnum.WAITING.getCode());
        inserSkuOrder.setType(SkuTypeEnum.SKU.getCode());
        inserSkuOrder.setCreateTime(new Date());
        inserSkuOrder.setBuyWay(SkuOrderBuyTypeEnum.CAR.getCode());
        inserSkuOrder.setIsDeliverGoods("N");
        inserSkuOrder.setSupplierId(0);
        inserSkuOrder.setOrderType(SkuOrderTypeEnum.PERIODIZATION.getCode());
        inserSkuOrder.setIsPay("N");
        inserSkuOrder.setPeriodsNumber(0);
        inserSkuOrder.setAppletType(req.getAppletType());
        skuOrderDao.insert(inserSkuOrder);
        for (PeriodizationSkuListReq periodizationSkuListReq : periodizationSkuListReqs) {
            Sku sku = skuDao.findById(periodizationSkuListReq.getSkuId());
            SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(periodizationSkuListReq.getSkuSalesInformationId());
            if (supplierId == null) {
                supplierId = sku.getSupplierId();
            }
            Double unitPrice = skuSalesInformation.getPrice();
            SkuOrder skuOrder = new SkuOrder();
            skuOrder.setType(SkuTypeEnum.SKU.getCode());
            Integer count = periodizationSkuListReq.getCount();
            //总价
            double payPrice = skuSalesInformation.getPrice() * count;
            double price = skuSalesInformation.getPrice() * count;
            RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(merchantCity.getCityId(), req.getCityId(), periodizationSkuListReq.getSkuSalesInformationId(), sku.getTitle());
            isRegion = "N";
            //计算区域价格
            if (regionalSkuSalesInformation != null) {
                payPrice = regionalSkuSalesInformation.getRegionalPrice() * count * regionalSkuSalesInformation.getDepositDeduction();
                price = regionalSkuSalesInformation.getRegionalPrice() * count;
                unitPrice = regionalSkuSalesInformation.getRegionalPrice();
                isRegion = "Y";
            }
            SkuOrderDetail insertSkuOrderDetail = new SkuOrderDetail();
            insertSkuOrderDetail.setSkuOrderId(inserSkuOrder.getId());
            insertSkuOrderDetail.setSkuId(periodizationSkuListReq.getSkuId());
            insertSkuOrderDetail.setSkuSalesInformationId(periodizationSkuListReq.getSkuSalesInformationId());
            insertSkuOrderDetail.setSupplierId(sku.getSupplierId());
            insertSkuOrderDetail.setMerchantId(req.getMerchantId());
            insertSkuOrderDetail.setPrice(unitPrice);
            insertSkuOrderDetail.setPayPrice(payPrice);
            insertSkuOrderDetail.setCount(periodizationSkuListReq.getCount());
            insertSkuOrderDetail.setDeliveryWay(DeliveryWayEnum.FREESHIPPING.getCode());
            insertSkuOrderDetail.setIntegral(0);
            insertSkuOrderDetail.setIsRegion(isRegion);
            insertSkuOrderDetail.setPeriodsNumber(0);
            skuOrderDetailDao.insert(insertSkuOrderDetail);
            totalPrice += price;
            totalPayPrice += payPrice;
            Integer s = 0;
            Pattern pattern = Pattern.compile("\\d+");
            Matcher matcher = pattern.matcher(skuSalesInformation.getSpecifications());
            while (matcher.find()) {
                s = Integer.parseInt(matcher.group());
                break;
            }
            SkuOrderDetailPeriodization skuOrderDetailPeriodization = new SkuOrderDetailPeriodization();
            skuOrderDetailPeriodization.setTotalOrderId(insertOrder.getId());
            skuOrderDetailPeriodization.setSkuOrderId(inserSkuOrder.getId());
            skuOrderDetailPeriodization.setSkuOrderDetailId(insertSkuOrderDetail.getId());
            skuOrderDetailPeriodization.setTotalSpecifications(s * count);
            skuOrderDetailPeriodization.setExtractSpecifications(0);
            skuOrderDetailPeriodization.setResidueSpecifications(req.getPeriodsNumber());
            skuOrderDetailPeriodization.setPeriodsNumber(0);
            skuOrderDetailPeriodization.setCreateTime(new Date());
            skuOrderDetailPeriodizationDao.insert(skuOrderDetailPeriodization);
        }
        SkuOrder updateSkuOrder = new SkuOrder();
        updateSkuOrder.setId(inserSkuOrder.getId());
        updateSkuOrder.setTotalPrice(totalPrice);
        updateSkuOrder.setPayPrice(totalPayPrice);
        updateSkuOrder.setIntegralPrice(0.0);
        updateSkuOrder.setIntegral(0);
        updateSkuOrder.setSupplierId(supplierId);
        updateSkuOrder.setIsRegion(isRegion);
        skuOrderDao.updateById(updateSkuOrder);
        Order param = new Order();
        param.setId(insertOrder.getId());
        param.setTotalPrice(totalPrice);
        param.setPayPrice(totalPayPrice);
        orderDao.updateById(param);
        Order newOrder = orderDao.findById(insertOrder.getId());
        BeanUtils.copyProperties(orderResult, newOrder);
        orderResult.setTotalPrice(totalPrice);
        orderResult.setPayPrice(new BigDecimal(totalPayPrice + "").setScale(2, RoundingMode.HALF_EVEN).doubleValue());
        orderResult.setOutOrderId(environment + OrderTypeEnum.PERIODIZATION.getCode() + "-" + inserSkuOrder.getId());
        return orderResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderResult addPeriodizationOrderReq(PeriodizationOrderReq req) throws BusinessException {
        OrderResult orderResult = new OrderResult();
        Map<Integer, PeriodizationSkuListReq> periodizationSkuListReqMap = req.getPeriodizationSkuListReqs().stream().collect(Collectors.toMap(PeriodizationSkuListReq::getSkuSalesInformationId, i -> i));
        Integer orderId = req.getOrderId();
        Order order = orderDao.findById(orderId);
        MerchantCity merchantCity = getMerchantCity(order.getMerchantCityId());
        Merchant merchant = merchantDao.findById(order.getMerchantId());
        ValidateBusinessException.assertFalse(SkuOrderStatusEnum.SUCCESS.getCode().equals(order.getStatus()), ExceptionEnum.ERROR_2007);
        SkuOrderQuery waitOrder = new SkuOrderQuery();
        waitOrder.setOrderId(orderId);
        waitOrder.setStatus(SkuOrderStatusEnum.WAITING.getCode());
        Integer count = skuOrderDao.count(waitOrder);
        ValidateBusinessException.assertFalse(count > 0, ExceptionEnum.ERROR_2004);
        SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
        skuOrderQuery.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
        skuOrderQuery.setReverseStatus(SkuOrderStatusEnum.CANCEL.getCode());
        skuOrderQuery.setOrderId(orderId);
        SkuOrder skuOrder = skuOrderDao.findFirst(skuOrderQuery);
        skuOrderQuery.setPeriodsNumber(0);
        SkuOrder firstSkuOrder = skuOrderDao.findFirst(skuOrderQuery);
        ValidateBusinessException.assertFalse(skuOrder.getPeriodsNumber() + 1 > order.getPeriodsNumber(), ExceptionEnum.ERROR_2006);
        SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
        skuOrderDetailQuery.setSkuOrderId(skuOrder.getId());
        List<SkuOrderDetail> skuOrderDetailList = skuOrderDetailDao.list(skuOrderDetailQuery);
        SkuOrderDetailPeriodizationQuery skuOrderDetailPeriodizationQuery = new SkuOrderDetailPeriodizationQuery();
        skuOrderDetailPeriodizationQuery.setSkuOrderId(skuOrder.getId());
        List<SkuOrderDetailPeriodization> skuOrderDetailPeriodizationList = skuOrderDetailPeriodizationDao.list(skuOrderDetailPeriodizationQuery);
        Map<Integer, SkuOrderDetailPeriodization> skuOrderDetailPeriodizationMap = skuOrderDetailPeriodizationList.stream().collect(Collectors.toMap(SkuOrderDetailPeriodization::getSkuOrderDetailId, i -> i));
        Double totalPayPrice = 0.0;
        SkuOrder inserSkuOrder = new SkuOrder();
        inserSkuOrder.setOrderId(orderId);
        inserSkuOrder.setMerchantId(skuOrder.getMerchantId());
        inserSkuOrder.setTotalPrice(skuOrder.getTotalPrice());
        inserSkuOrder.setSupplierId(skuOrder.getSupplierId());
        inserSkuOrder.setPayPrice(0.0);
        inserSkuOrder.setIntegralPrice(0.0);
        inserSkuOrder.setIntegral(0);
        inserSkuOrder.setStatus(SkuOrderStatusEnum.WAITING.getCode());
        inserSkuOrder.setType(SkuTypeEnum.SKU.getCode());
        inserSkuOrder.setCreateTime(new Date());
        inserSkuOrder.setBuyWay(SkuOrderBuyTypeEnum.CAR.getCode());
        inserSkuOrder.setIsDeliverGoods("N");
        inserSkuOrder.setOrderType(SkuOrderTypeEnum.PERIODIZATION.getCode());
        inserSkuOrder.setIsPay("N");
        inserSkuOrder.setPeriodsNumber(skuOrder.getPeriodsNumber() + 1);
        inserSkuOrder.setAppletType(req.getAppletType());
        skuOrderDao.insert(inserSkuOrder);
        List<SkuOrderDetail> skuOrderDetails = new ArrayList<>();
        for (SkuOrderDetail skuOrderDetail : skuOrderDetailList) {
            SkuOrderDetailQuery skuOrderDetailQuery1 = new SkuOrderDetailQuery();
            skuOrderDetailQuery1.setSkuOrderId(firstSkuOrder.getId());
            skuOrderDetailQuery1.setSkuSalesInformationId(skuOrderDetail.getSkuSalesInformationId());
            SkuOrderDetail first = skuOrderDetailDao.findFirst(skuOrderDetailQuery1);
            PeriodizationSku periodizationSku = periodizationSkuDao.findBySkuId(skuOrderDetail.getSkuId());
            SkuOrderDetailPeriodization skuOrderDetailPeriodization = skuOrderDetailPeriodizationMap.get(skuOrderDetail.getId());
            ValidateBusinessException.assertNonNull(skuOrderDetailPeriodization, ExceptionEnum.ERROR_2005);
            PeriodizationSkuListReq periodizationSkuListReq = periodizationSkuListReqMap.get(skuOrderDetail.getSkuSalesInformationId());
            Integer count1 = periodizationSkuListReq.getCount();
            if ((skuOrder.getPeriodsNumber() + 1) == order.getPeriodsNumber() && periodizationSku != null) {
                ValidateBusinessException.assertFalse(!skuOrderDetailPeriodization.getResidueSpecifications().equals(count1), ExceptionEnum.ERROR_2008);
            }
            if (periodizationSku != null && skuOrderDetailPeriodization != null && skuOrderDetailPeriodization.getResidueSpecifications() <= 0) {
                throw BusinessException.build(ExceptionEnum.ERROR_2011);
            }
            ValidateBusinessException.assertFalse(skuOrderDetailPeriodization.getResidueSpecifications() < count1, ExceptionEnum.ERROR_2009);
            SkuOrderDetail insertSkuOrderDetail = new SkuOrderDetail();
            insertSkuOrderDetail.setSkuOrderId(inserSkuOrder.getId());
            insertSkuOrderDetail.setSkuId(skuOrderDetail.getSkuId());
            insertSkuOrderDetail.setSkuSalesInformationId(skuOrderDetail.getSkuSalesInformationId());
            insertSkuOrderDetail.setSupplierId(skuOrderDetail.getSupplierId());
            insertSkuOrderDetail.setMerchantId(skuOrderDetail.getMerchantId());
            insertSkuOrderDetail.setPrice(skuOrderDetail.getPrice());
            insertSkuOrderDetail.setCount(skuOrderDetail.getCount());
            double payPrice = new BigDecimal(skuOrderDetail.getPrice() + "").multiply(new BigDecimal(skuOrderDetail.getCount() + ""))
                    .subtract(new BigDecimal(first.getPayPrice() + "")).multiply(new BigDecimal(count1)).divide(new BigDecimal(order.getPeriodsNumber()), 2, RoundingMode.HALF_EVEN).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            logger.info("payPrice===" + payPrice + ",price===" + skuOrderDetail.getPrice() +
                    ",getCount=====" + skuOrderDetail.getCount() + ",getPayPrice===" +
                    first.getPayPrice() + ",periodizationSkuListReq====" + count1 +
                    ",TotalSpecifications===" + order.getPeriodsNumber());
            if ((skuOrder.getPeriodsNumber() + 1) == order.getPeriodsNumber() && periodizationSku != null) {
                Double payPrice1 = skuOrderDetailDao.getPayPrice(orderId, skuOrderDetail.getSkuSalesInformationId());
                payPrice = new BigDecimal(skuOrderDetail.getPrice() + "").multiply(new BigDecimal(skuOrderDetail.getCount() + "")).subtract(new BigDecimal(payPrice1 + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            }
            insertSkuOrderDetail.setPayPrice(payPrice);
            insertSkuOrderDetail.setDeliveryWay(DeliveryWayEnum.FREESHIPPING.getCode());
            insertSkuOrderDetail.setIntegral(0);
            insertSkuOrderDetail.setIsRegion("Y");
            insertSkuOrderDetail.setPeriodsNumber(skuOrder.getPeriodsNumber() + 1);
            skuOrderDetails.add(insertSkuOrderDetail);
            skuOrderDetailDao.insert(insertSkuOrderDetail);
            totalPayPrice = new BigDecimal(totalPayPrice + "").add(new BigDecimal(payPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            SkuOrderDetailPeriodization insertSkuOrderDetailPeriodization = new SkuOrderDetailPeriodization();
            insertSkuOrderDetailPeriodization.setTotalOrderId(inserSkuOrder.getOrderId());
            insertSkuOrderDetailPeriodization.setSkuOrderId(inserSkuOrder.getId());
            insertSkuOrderDetailPeriodization.setSkuOrderDetailId(insertSkuOrderDetail.getId());
            insertSkuOrderDetailPeriodization.setTotalSpecifications(skuOrderDetailPeriodization.getTotalSpecifications());
            insertSkuOrderDetailPeriodization.setExtractSpecifications(count1 * skuOrderDetailPeriodization.getTotalSpecifications() / order.getPeriodsNumber());
            insertSkuOrderDetailPeriodization.setResidueSpecifications(skuOrderDetailPeriodization.getResidueSpecifications() - count1);
            insertSkuOrderDetailPeriodization.setPeriodsNumber(skuOrder.getPeriodsNumber() + 1);
            insertSkuOrderDetailPeriodization.setCreateTime(new Date());
            skuOrderDetailPeriodizationDao.insert(insertSkuOrderDetailPeriodization);
        }
        SkuOrder updateSkuOrder = new SkuOrder();
        updateSkuOrder.setId(inserSkuOrder.getId());
        updateSkuOrder.setPayPrice(totalPayPrice);
        skuOrderDao.updateById(updateSkuOrder);
        BeanUtils.copyProperties(orderResult, order);
        orderResult.setTotalPrice(order.getTotalPrice());
        orderResult.setPayPrice(totalPayPrice);
        orderResult.setOutOrderId(environment + OrderTypeEnum.PERIODIZATION.getCode() + "-" + inserSkuOrder.getId());
        //添加分佣信息
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Integer fengyongMerchantId = null;
                    Double fengyongProportion = 0.0;
                    Double fengxiaoProportion = null;
                    DailiMerchantQuery param = new DailiMerchantQuery();
                    param.setMobile(merchant.getMobile());
                    param.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
                    param.setIsEnable("Y");
                    DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(param);
                    if (dailiMerchant == null) {
                        throw BusinessException.build(ExceptionEnum.ERROR_1902);
                    }
                    if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(dailiMerchant.getRole())) {
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        fengxiaoProportion = dailiMerchant.getProportion();
                        fengyongMerchantId = dailiMerchant.getPid();
                    } else if (DailiMerchantRoleEnum.MERCHANT.getCode().equals(dailiMerchant.getRole())) {
                        fengyongMerchantId = Integer.parseInt(dailiMerchant.getPidPath().split(",")[0]);
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(secondMerchant.getRole())) {
                            DailiMerchant thirdMerchant = dailiMerchantDao.findById(secondMerchant.getPid());
                            if (!"Y".equals(thirdMerchant.getIsEnable())) {
                                throw BusinessException.build(ExceptionEnum.ERROR_1902);
                            }
                            fengxiaoProportion = secondMerchant.getProportion();
                        }
                    } else {
                        fengyongMerchantId = dailiMerchant.getId();
                    }
                    logger.info("aaaaaaaaaaaa");
                    for (SkuOrderDetail skuOrderDetail : skuOrderDetails) {
                        logger.info("skuOrderDetail" + JSONObject.toJSONString(skuOrderDetail));
                        DailiMerchantSkuQuery dailiMerchantSkuQuery = new DailiMerchantSkuQuery();
                        dailiMerchantSkuQuery.setDailiMerchantId(fengyongMerchantId);
                        dailiMerchantSkuQuery.setSkuId(skuOrderDetail.getSkuId());
                        DailiMerchantSku dailiMerchantSku = dailiMerchantSkuDao.findFirst(dailiMerchantSkuQuery);
                        if (dailiMerchantSku != null) {
                            fengyongProportion = dailiMerchantSku.getProportion();
                            RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(merchantCity.getCityId(), req.getCityId(), skuOrderDetail.getSkuSalesInformationId(), dailiMerchantSku.getTitle());
                            if (regionalSkuSalesInformation != null && regionalSkuSalesInformation.getProportion() != null) {
                                fengyongProportion = regionalSkuSalesInformation.getProportion();

                            }
                            DailiOrder dailiOrder = new DailiOrder();
                            dailiOrder.setOrderId(skuOrderDetail.getId());
                            dailiOrder.setDailiMerchantId(dailiMerchant.getId());
                            dailiOrder.setDailiPidPath(dailiMerchant.getPidPath());
                            dailiOrder.setSkuId(skuOrderDetail.getSkuId());
                            dailiOrder.setOrderAmount(skuOrderDetail.getPrice());
                            dailiOrder.setPayAmount(skuOrderDetail.getPayPrice());
                            double fengyongAmount = new BigDecimal(skuOrderDetail.getPayPrice() + "").multiply(new BigDecimal(fengyongProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                            dailiOrder.setFengyongAmount(fengyongAmount);
                            if (fengxiaoProportion != null) {
                                double fenxiaoyuanAmount = new BigDecimal(fengyongAmount + "").multiply(new BigDecimal(fengxiaoProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                                dailiOrder.setFengxiaoyuanAmount(fenxiaoyuanAmount);
                                dailiOrder.setFengyongAmount(new BigDecimal(fengyongAmount + "").subtract(new BigDecimal(fenxiaoyuanAmount + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
                            }
                            dailiOrder.setCreateTime(new Date());
                            dailiOrder.setDate(DateUtil.date(new Date(), "yyyy-MM"));
                            dailiOrderDao.insert(dailiOrder);
                        }
                    }
                } catch (BusinessException e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                }
            }
        });
        return orderResult;
    }

    @Override
    public Map<Object, Object> getPeriodizationPrice(PeriodizationOrderReq req) throws BusinessException {
        Map<Object, Object> map = new HashMap<>();
        Map<Integer, PeriodizationSkuListReq> periodizationSkuListReqMap = req.getPeriodizationSkuListReqs().stream().collect(Collectors.toMap(PeriodizationSkuListReq::getSkuSalesInformationId, i -> i));
        Integer orderId = req.getOrderId();
        Order order = orderDao.findById(orderId);
        map.put("address", order.getAddress());
        map.put("receiver", order.getReceiver());
        map.put("receiverMobile", order.getReceiverMobile());
        SkuOrderQuery waitOrder = new SkuOrderQuery();
        waitOrder.setOrderId(orderId);
        waitOrder.setStatus(SkuOrderStatusEnum.WAITING.getCode());
        Integer count = skuOrderDao.count(waitOrder);
        ValidateBusinessException.assertFalse(count > 0, ExceptionEnum.ERROR_2004);
        SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
        skuOrderQuery.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
        skuOrderQuery.setReverseStatus(SkuOrderStatusEnum.CANCEL.getCode());
        skuOrderQuery.setOrderId(orderId);
        SkuOrder skuOrder = skuOrderDao.findFirst(skuOrderQuery);
        skuOrderQuery.setPeriodsNumber(0);
        SkuOrder firstSkuOrder = skuOrderDao.findFirst(skuOrderQuery);
        SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
        skuOrderDetailQuery.setSkuOrderId(skuOrder.getId());
        List<SkuOrderDetail> skuOrderDetailList = skuOrderDetailDao.list(skuOrderDetailQuery);
        SkuOrderDetailPeriodizationQuery skuOrderDetailPeriodizationQuery = new SkuOrderDetailPeriodizationQuery();
        skuOrderDetailPeriodizationQuery.setSkuOrderId(skuOrder.getId());
        List<SkuOrderDetailPeriodization> skuOrderDetailPeriodizationList = skuOrderDetailPeriodizationDao.list(skuOrderDetailPeriodizationQuery);
        Map<Integer, SkuOrderDetailPeriodization> skuOrderDetailPeriodizationMap = skuOrderDetailPeriodizationList.stream().collect(Collectors.toMap(SkuOrderDetailPeriodization::getSkuOrderDetailId, i -> i));
        Double totalPayPrice = 0.0;
        for (SkuOrderDetail skuOrderDetail : skuOrderDetailList) {
            SkuOrderDetailQuery skuOrderDetailQuery1 = new SkuOrderDetailQuery();
            skuOrderDetailQuery1.setSkuOrderId(firstSkuOrder.getId());
            skuOrderDetailQuery1.setSkuSalesInformationId(skuOrderDetail.getSkuSalesInformationId());
            SkuOrderDetail first = skuOrderDetailDao.findFirst(skuOrderDetailQuery1);
            PeriodizationSku periodizationSku = periodizationSkuDao.findBySkuId(skuOrderDetail.getSkuId());
            SkuOrderDetailPeriodization skuOrderDetailPeriodization = skuOrderDetailPeriodizationMap.get(skuOrderDetail.getId());
            ValidateBusinessException.assertNonNull(skuOrderDetailPeriodization, ExceptionEnum.ERROR_2005);
            PeriodizationSkuListReq periodizationSkuListReq = periodizationSkuListReqMap.get(skuOrderDetail.getSkuSalesInformationId());
            if ((skuOrder.getPeriodsNumber() + 1) == order.getPeriodsNumber() && periodizationSku != null) {
                ValidateBusinessException.assertFalse(!skuOrderDetailPeriodization.getResidueSpecifications().equals(periodizationSkuListReq.getCount()), ExceptionEnum.ERROR_2008);
            }
            ValidateBusinessException.assertFalse(skuOrderDetailPeriodization.getResidueSpecifications() < periodizationSkuListReq.getCount(), ExceptionEnum.ERROR_2009);
            double payPrice = new BigDecimal(skuOrderDetail.getPrice() + "").multiply(new BigDecimal(skuOrderDetail.getCount() + ""))
                    .subtract(new BigDecimal(first.getPayPrice() + "")).multiply(new BigDecimal(periodizationSkuListReq.getCount() + "")).divide(new BigDecimal(order.getPeriodsNumber()), 2, RoundingMode.HALF_EVEN).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            logger.info("payPrice===" + payPrice + ",price===" + skuOrderDetail.getPrice() + ",getCount=====" + skuOrderDetail.getCount() + ",getPayPrice===" + first.getPayPrice() + ",periodizationSkuListReq====" + periodizationSkuListReq.getCount() + ",TotalSpecifications===" + order.getPeriodsNumber());
            if ((skuOrder.getPeriodsNumber() + 1) == order.getPeriodsNumber() && periodizationSku != null) {
                Double payPrice1 = skuOrderDetailDao.getPayPrice(orderId, skuOrderDetail.getSkuSalesInformationId());
                payPrice = new BigDecimal(skuOrderDetail.getPrice() + "").multiply(new BigDecimal(skuOrderDetail.getCount() + "")).subtract(new BigDecimal(payPrice1 + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            }
            map.put(skuOrderDetail.getSkuId(), payPrice);
            totalPayPrice = new BigDecimal(totalPayPrice + "").add(new BigDecimal(payPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
        }
        map.put("totalPrice", totalPayPrice);
        return map;
    }

    @Override
    public void finishEnjoyOrder(List<Integer> ids) {
        for (Integer id : ids) {
            SkuOrder skuOrder = skuOrderDao.findById(id);
            if (SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrder.getOrderType()) && (SkuOrderStatusEnum.PAY.getCode().equals(skuOrder.getStatus()) || SkuOrderStatusEnum.DELIVER.getCode().equals(skuOrder.getStatus()))) {
                SkuOrder updateSku = new SkuOrder();
                updateSku.setId(skuOrder.getId());
                updateSku.setStatus(SkuOrderStatusEnum.SUCCESS.getCode());
                updateSku.setFinishTime(new Date());
                updateSku.setIsPay("Y");
                skuOrderDao.updateById(updateSku);
            } else {
                continue;
            }
        }
    }

    @Override
    public void modifyPrice(Integer skuOrderId, Integer skuOrderDetailId, Double price) throws BusinessException {
        SkuOrder skuOrder = skuOrderDao.findById(skuOrderId);
        ValidateBusinessException.assertTrue(SkuOrderStatusEnum.WAITING.getCode().equals(skuOrder.getStatus()), ExceptionEnum.ERROR_1876);
        SkuOrderDetail skuOrderDetail = new SkuOrderDetail();
        skuOrderDetail.setId(skuOrderDetailId);
        skuOrderDetail.setModifyPrice(price);
        skuOrderDetail.setIsModifyPrice("Y");
        skuOrderDetail.setModifyTime(new Date());
        skuOrderDetailDao.updateModifyPriceById(skuOrderDetail);
        skuOrder = new SkuOrder();
        skuOrder.setId(skuOrderId);
        skuOrder.setIsModifyPrice("Y");
        skuOrderDao.updateModifyPriceByOrderId(skuOrder);
    }

    @Override
    public CarPriceResult getIntegralPrice(Integer cityId, Integer merchantId, List<Integer> skuShopcarId, String isUseIntegral) throws BusinessException {
        CarPriceResult carPriceResult = new CarPriceResult();
        List<CarPriceDetailResult> carPriceDetailResults = new ArrayList<>();
        Merchant merchant = merchantDao.findById(merchantId);
        PlatformSystemDeploy platformSystemDeploy = jfPlatformSystemDeploy();
        //总价
        Double totalPrice = 0.0;
        //支付价格
        Double totalPayPrice = 0.0;
        //积分价格
        Double integerPrice = 0.0;
        //总积分价格
        Double totalIntegerPrice = 0.0;
        //积分
        Integer integralPrice = 0;
        //商户积分
        Integer merchantIntegral = merchant.getIntegral();
        //满减商品的金额
        Double fullReductionPrice = 0.0;
        List<SkuShopcar> skuShopcars = skuShopcarDao.findByIds(skuShopcarId);
        for (SkuShopcar skuShopcar : skuShopcars) {
            CarPriceDetailResult carPriceDetailResult = new CarPriceDetailResult();
            ValidateBusinessException.assertTrue(merchantId.equals(skuShopcar.getMerchantId()), ExceptionEnum.ERROR_1853);
            Integer count = skuShopcar.getCount();
            Sku sku = skuDao.findById(skuShopcar.getSkuId());
            ValidateBusinessException.assertNonNull(sku, ExceptionEnum.ERROR_1701);
            ValidateBusinessException.assertFalse("N".equals(sku.getIsEnable()), ExceptionEnum.ERROR_1702);
            SkuContent skuContent = skuContentDao.findBySkuId(skuShopcar.getSkuId());
            ValidateBusinessException.assertNonNull(skuContent, ExceptionEnum.ERROR_1701);
            ValidateBusinessException.assertFalse("Y".equals(skuContent.getIsSpellOrder()), ExceptionEnum.ERROR_1707);
            SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuShopcar.getSkuSalesInformationId());
            ValidateBusinessException.assertNonNull(skuSalesInformation, ExceptionEnum.ERROR_1703);
            Double price = new BigDecimal(skuSalesInformation.getPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            RegionalSkuSalesInformation regionalSkuSalesInformation = new RegionalSkuSalesInformation();
            if (cityId != null) {
                RegionalSkuSalesInformationQuery regionalSkuSalesInformationQuery = new RegionalSkuSalesInformationQuery();
                regionalSkuSalesInformationQuery.setGtRegionId(cityId);
                regionalSkuSalesInformationQuery.setSkuSalesInformationId(skuShopcar.getSkuSalesInformationId());
                regionalSkuSalesInformation = regionalSkuSalesInformationDao.findFirst(regionalSkuSalesInformationQuery);
                if (regionalSkuSalesInformation != null) {
                    price = new BigDecimal(regionalSkuSalesInformation.getRegionalPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                }
            }
            totalPrice += price;
            if ("Y".equals(skuContent.getIsIntegral()) && "Y".equals(isUseIntegral)) {
                Double integralDeduction = skuContent.getIntegralDeduction();
                if (skuSalesInformation.getIntegralDeduction() != null) {
                    integralDeduction = skuSalesInformation.getIntegralDeduction();
                }
                if (regionalSkuSalesInformation != null && regionalSkuSalesInformation.getIntegralDeduction() != null) {
                    integralDeduction = regionalSkuSalesInformation.getIntegralDeduction();
                }
                integerPrice = new BigDecimal(price + "").multiply(new BigDecimal(integralDeduction)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                Integer integral = new BigDecimal(integerPrice + "").divide(new BigDecimal(platformSystemDeploy.getDetails()), BigDecimal.ROUND_HALF_EVEN).multiply(new BigDecimal(platformSystemDeploy.getUnit())).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                if (merchantIntegral > integral) {
                    integralPrice = integral;
                } else if (merchantIntegral > 0) {
                    integralPrice = merchantIntegral;
                    integerPrice = new BigDecimal(merchantIntegral).divide(new BigDecimal(platformSystemDeploy.getUnit()), 2, BigDecimal.ROUND_HALF_EVEN)
                            .multiply(new BigDecimal(platformSystemDeploy.getDetails())).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                } else {
                    integralPrice = 0;
                    integerPrice = 0.0;
                }
                carPriceDetailResult.setSkuShopcarId(skuShopcar.getId());
                carPriceDetailResult.setSkuName(sku.getTitle());
                carPriceDetailResult.setIntegralPrice(integralPrice);
                carPriceDetailResult.setIntegerPrice(integerPrice);
                carPriceDetailResults.add(carPriceDetailResult);
            } else if ("Y".equals(skuContent.getIsIntegral()) && "N".equals(isUseIntegral)) {
                carPriceDetailResult.setSkuShopcarId(skuShopcar.getId());
                carPriceDetailResult.setSkuName(sku.getTitle());
                carPriceDetailResult.setIntegralPrice(0);
                carPriceDetailResult.setIntegerPrice(0.0);
                carPriceDetailResults.add(carPriceDetailResult);
                integralPrice = 0;
                integerPrice = 0.0;
            } else {
                integralPrice = 0;
                integerPrice = 0.0;
            }
            merchantIntegral -= integralPrice;
            logger.info("integralPrice===" + integralPrice + ",skuId=====" + JSONObject.toJSONString(skuShopcar));
            double payPrice = 0.0;
            if (price >= integerPrice) {
                payPrice = new BigDecimal(price).subtract(new BigDecimal(integerPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            }
            if (skuContent.getLogistics().equals(DeliveryWayEnum.FULLREDUCTION.getCode())) {
                fullReductionPrice += payPrice;
            }
            totalPayPrice += payPrice;
            totalIntegerPrice += integerPrice;
        }
        carPriceResult.setTotalPrice(new BigDecimal(totalPrice + "").setScale(2, RoundingMode.HALF_EVEN).doubleValue());
        carPriceResult.setTotalPayPrice(new BigDecimal(totalPayPrice + "").setScale(2, RoundingMode.HALF_EVEN).doubleValue());
        carPriceResult.setIntegerPrice(new BigDecimal(totalIntegerPrice + "").setScale(2, RoundingMode.HALF_EVEN).doubleValue());
        carPriceResult.setCarPriceDetailResults(carPriceDetailResults);
        if (fullReductionPrice > 0.0) {
            UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
            urbanFullReductionQuery.setCityId(cityId);
            UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            if (urbanFullReductionDaoFirst == null) {
                urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            }
            carPriceResult.setDifferencePrice(new BigDecimal(urbanFullReductionDaoFirst.getMoney() + "").subtract(new BigDecimal(fullReductionPrice + "").setScale(2, RoundingMode.HALF_EVEN)).doubleValue());
            carPriceResult.setFullReductionPrice(urbanFullReductionDaoFirst.getMoney());
            carPriceResult.setFreight(urbanFullReductionDaoFirst.getFreight());
            if (fullReductionPrice < urbanFullReductionDaoFirst.getMoney()) {
                carPriceResult.setTotalPayPrice(new BigDecimal(carPriceResult.getTotalPayPrice()).add(new BigDecimal(urbanFullReductionDaoFirst.getFreight() + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
            }
        }
        return carPriceResult;
    }

    @Override
    public CarPriceResult getIntegralBySku(Integer cityId, Integer merchantId, Integer skuId, Integer skuSalesInformationId, Integer count, String isSpellOrder, String isUseIntegral) throws BusinessException {
        CarPriceResult carPriceResult = new CarPriceResult();
        Merchant merchant = merchantDao.findById(merchantId);
        PlatformSystemDeploy platformSystemDeploy = jfPlatformSystemDeploy();
        //总价
        Double totalPrice = 0.0;
        //支付价格
        Double totalPayPrice = 0.0;
        //积分价格
        Double integerPrice = 0.0;
        //积分
        Integer integralPrice = 0;
        //商户积分
        Integer merchantIntegral = merchant.getIntegral();
        Sku sku = skuDao.findById(skuId);
        ValidateBusinessException.assertNonNull(sku, ExceptionEnum.ERROR_1701);
        ValidateBusinessException.assertFalse("N".equals(sku.getIsEnable()), ExceptionEnum.ERROR_1702);
        SkuContent skuContent = skuContentDao.findBySkuId(skuId);
        ValidateBusinessException.assertNonNull(skuContent, ExceptionEnum.ERROR_1701);
        SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuSalesInformationId);
        ValidateBusinessException.assertNonNull(skuSalesInformation, ExceptionEnum.ERROR_1703);
        totalPrice = new BigDecimal(skuSalesInformation.getPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
        RegionalSkuSalesInformation regionalSkuSalesInformation = new RegionalSkuSalesInformation();
        if (cityId != null) {
            RegionalSkuSalesInformationQuery regionalSkuSalesInformationQuery = new RegionalSkuSalesInformationQuery();
            regionalSkuSalesInformationQuery.setGtRegionId(cityId);
            regionalSkuSalesInformationQuery.setSkuSalesInformationId(skuSalesInformationId);
            regionalSkuSalesInformation = regionalSkuSalesInformationDao.findFirst(regionalSkuSalesInformationQuery);
            if (regionalSkuSalesInformation != null) {
                totalPrice = new BigDecimal(regionalSkuSalesInformation.getRegionalPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            }
        }
        if ("Y".equals(isSpellOrder)) {
            totalPrice = new BigDecimal(skuSalesInformation.getSpellOrderPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
        }
        if ("Y".equals(skuContent.getIsIntegral()) && "Y".equals(isUseIntegral)) {
            Double integralDeduction = skuContent.getIntegralDeduction();
            if (skuSalesInformation.getIntegralDeduction() != null) {
                integralDeduction = skuSalesInformation.getIntegralDeduction();
            }
            if (regionalSkuSalesInformation != null && regionalSkuSalesInformation.getIntegralDeduction() != null) {
                integralDeduction = regionalSkuSalesInformation.getIntegralDeduction();
            }
            if (integralDeduction == null) {
                integralDeduction = 0.0;
            }
            integerPrice = new BigDecimal(totalPrice + "").multiply(new BigDecimal(integralDeduction)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            Integer integral = new BigDecimal(integerPrice + "").divide(new BigDecimal(platformSystemDeploy.getDetails()), BigDecimal.ROUND_HALF_EVEN).multiply(new BigDecimal(platformSystemDeploy.getUnit())).setScale(0, BigDecimal.ROUND_UP).intValue();
            if (merchantIntegral > integral) {
                integralPrice = integral;
            } else if (merchantIntegral > 0) {
                integralPrice = merchantIntegral;
                integerPrice = new BigDecimal(merchantIntegral).divide(new BigDecimal(platformSystemDeploy.getUnit()), 2, BigDecimal.ROUND_HALF_EVEN)
                        .multiply(new BigDecimal(platformSystemDeploy.getDetails())).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            } else {
                integralPrice = 0;
                integerPrice = 0.0;
            }
        } else {
            integralPrice = 0;
        }
        if (totalPrice >= integerPrice) {
            totalPayPrice = new BigDecimal(totalPrice).subtract(new BigDecimal(integerPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
        }
        carPriceResult.setTotalPrice(new BigDecimal(totalPrice + "").setScale(2, RoundingMode.HALF_EVEN).doubleValue());
        carPriceResult.setTotalPayPrice(new BigDecimal(totalPayPrice + "").setScale(2, RoundingMode.HALF_EVEN).doubleValue());
        carPriceResult.setIntegerPrice(new BigDecimal(integerPrice + "").setScale(2, RoundingMode.HALF_EVEN).doubleValue());
        carPriceResult.setIntegralPrice(integralPrice);
        if (skuContent.getLogistics().equals(DeliveryWayEnum.FULLREDUCTION.getCode())) {
            UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
            urbanFullReductionQuery.setCityId(cityId);
            UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            if (urbanFullReductionDaoFirst == null) {
                urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            }
            carPriceResult.setDifferencePrice(new BigDecimal(urbanFullReductionDaoFirst.getMoney() + "").subtract(new BigDecimal(totalPayPrice + "").setScale(2)).doubleValue());
            carPriceResult.setFullReductionPrice(urbanFullReductionDaoFirst.getMoney());
            carPriceResult.setFreight(urbanFullReductionDaoFirst.getFreight());
            if (carPriceResult.getTotalPayPrice() < urbanFullReductionDaoFirst.getMoney()) {
                carPriceResult.setTotalPayPrice(new BigDecimal(carPriceResult.getTotalPayPrice()).add(new BigDecimal(urbanFullReductionDaoFirst.getFreight() + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
            }

        }

        return carPriceResult;
    }

    public PlatformSystemDeploy jfPlatformSystemDeploy() throws BusinessException {
        PlatformSystemDeployQuery platformSystemDeployQuery = new PlatformSystemDeployQuery();
        platformSystemDeployQuery.setType(SkuTypeEnum.INTEGRAL.getCode());
        platformSystemDeployQuery.setStatus(IntegralOperationEnum.DEDUCTION.getCode());
        PlatformSystemDeploy platformSystemDeploy = platformSystemDeployDao.findFirst(platformSystemDeployQuery);
        ValidateBusinessException.assertNonNull(platformSystemDeploy, ExceptionEnum.ERROR_1704);
        return platformSystemDeploy;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderResult continuePay(Integer skuOrderId, Integer merchantId, Integer merchantCityId, Integer cityId, String isBalance) throws BusinessException {
        List<SkuOrderDetail> skuOrderDetailLists = new ArrayList<>();
        OrderResult orderResult = new OrderResult();
        List<String> skuNames = new ArrayList<>();
        Merchant merchant = merchantDao.findByIdForUpdate(merchantId);
        if ("Y".equals(isBalance)&&merchant.getBalance()<=0.0){
            throw new BusinessException(ExceptionEnum.ERROR_1714.getCode(), ExceptionEnum.ERROR_1714.getMessage());
        }
        SkuOrder skuOrder = skuOrderDao.findByIdAndMerchantId(skuOrderId, merchantId);
        ValidateBusinessException.assertNonNull(skuOrder, ExceptionEnum.ERROR_1801);
        Order totalOrder = orderDao.findById(skuOrder.getOrderId());
        MerchantCity merchantCity = getMerchantCity(merchantCityId);
        MerchantCity orderMerchantCity = getMerchantCity(totalOrder.getMerchantCityId());
        orderResult.setId(skuOrderId);
        //判断继续支付地址是否修改
        if ("Y".equals(skuOrder.getIsRegion()) && orderMerchantCity.getCityId() != merchantCity.getCityId()) {
            throw BusinessException.build(ExceptionEnum.ERROR_1873);
        }

        if ("Y".equals(skuOrder.getIsModifyPrice())) {
            SkuOrder updateSkuOrder = new SkuOrder();
            updateSkuOrder.setId(skuOrder.getId());
            updateSkuOrder.setType(OrderTypeEnum.CAR.getCode().equals(skuOrder.getType()) ? OrderTypeEnum.SKU.getCode() : skuOrder.getType());
            updateSkuOrder.setBuyWay(OrderTypeEnum.CAR.getCode().equals(skuOrder.getType()) ? OrderTypeEnum.SKU.getCode() : skuOrder.getType());
            skuOrderDao.updateById(updateSkuOrder);
            Double payPrice = 0.0;
            if (SkuOrderTypeEnum.PERIODIZATION.getCode().equals(skuOrder.getOrderType())) {
                orderResult.setOutOrderId(environment + OrderTypeEnum.PERIODIZATION.getCode() + "-" + skuOrderId);
            } else if (SkuOrderTypeEnum.BUY.getCode().equals(skuOrder.getOrderType())) {
                orderResult.setOutOrderId(environment + OrderTypeEnum.SKU.getCode() + "-" + skuOrderId);
            } else {
                orderResult.setOutOrderId(environment + SkuOrderTypeEnum.ENJOY.getCode() + "-" + skuOrderId);
            }
            orderResult.setTotalPrice(skuOrder.getTotalPrice());
            orderResult.setIntegral(skuOrder.getIntegral());
            orderResult.setIntegralPrice(skuOrder.getIntegralPrice());
            orderResult.setOrderType(skuOrder.getType());
            orderResult.setSkuNames(skuNames);
            SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
            skuOrderDetailQuery.setSkuOrderId(skuOrderId);
            List<SkuOrderDetail> list = skuOrderDetailDao.list(skuOrderDetailQuery);
            for (SkuOrderDetail skuOrderDetail : list) {
                RegionalSku regionalSku = regionalSkuDao.findBySkuId(skuOrderDetail.getSkuId());
                if (regionalSku != null) {
                    if ("N".equals(isBalance) && "Y".equals(regionalSku.getIsMembersExclusive())) {
                        Sku sku = skuDao.findById(skuOrderDetail.getSkuId());
                        throw new BusinessException(ExceptionEnum.ERROR_1713.getCode(), sku.getTitle() + "," + ExceptionEnum.ERROR_1713.getMessage());
                    }
                }
                if ("Y".equals(skuOrderDetail.getIsModifyPrice())) {
                    payPrice += skuOrderDetail.getModifyPrice();
                } else {
                    payPrice += skuOrderDetail.getPayPrice();
                }
            }
            orderResult.setPayPrice(payPrice);
        } else {
            if (SkuOrderTypeEnum.BUY.getCode().equals(skuOrder.getOrderType()) || SkuOrderTypeEnum.PERIODIZATION.getCode().equals(skuOrder.getOrderType())) {
                Double fullReductionPrice = 0.0;
                SkuOrderDetailQuery param = new SkuOrderDetailQuery();
                param.setSkuOrderId(skuOrder.getId());
                List<SkuOrderDetail> skuOrderDetailList = skuOrderDetailDao.list(param);
                for (SkuOrderDetail skuOrderDetail : skuOrderDetailList) {
                    SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuOrderDetail.getSkuSalesInformationId());
                    if (skuSalesInformation.getStock() < skuOrderDetail.getCount()) {
                        throw new BusinessException(ExceptionEnum.ERROR_1816.getCode(), ExceptionEnum.ERROR_1816.getMessage());
                    }
                    Sku sku = skuDao.findById(skuOrderDetail.getSkuId());
                    RegionalSku regionalSku = regionalSkuDao.findBySkuId(sku.getId());
                    if (regionalSku != null) {
                        if ("N".equals(isBalance) && "Y".equals(regionalSku.getIsMembersExclusive())) {
                            throw new BusinessException(ExceptionEnum.ERROR_1713.getCode(), sku.getTitle() + "," + ExceptionEnum.ERROR_1713.getMessage());
                        }
                    }
                    skuNames.add(sku.getTitle());
                }
                //拼团商品判断是否可以继续支付
                if (SkuTypeEnum.PART.getCode().equals(skuOrder.getType())) {
                    SkuOrderDetail skuOrderDetail = skuOrderDetailList.get(0);
                    SkuContent skuContent = skuContentDao.findBySkuId(skuOrderDetail.getSkuId());
                    SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
                    skuOrderQuery.setPartSn(skuOrder.getPartSn());
                    skuOrderQuery.setIsSponsor("Y");
                    SkuOrder partOrder = skuOrderDao.findFirst(skuOrderQuery);
                    if (partOrder != null && SkuOrderStatusEnum.SUCCESS.getCode().equals(partOrder.getPartStatus())) {
                        throw new BusinessException(ExceptionEnum.ERROR_1861.getCode(), ExceptionEnum.ERROR_1861.getMessage());
                    }
                    if (!merchantCity.getProvinceId().equals(skuContent.getSpellOrderProvinceId()) || !merchantCity.getCityId().equals(skuContent.getSpellOrderCityId())) {
                        throw new BusinessException(ExceptionEnum.ERROR_1857.getCode(), ExceptionEnum.ERROR_1857.getMessage());
                    }
                }
                Double totalPrice = 0.0;
                Double totalPayPrice = 0.0;
                Integer totalIntegral = 0;
                Integer integralPrice = merchant.getIntegral();//查看积分抵扣金额
                if (integralPrice >= skuOrder.getIntegral()) {
                    orderResult.setOutOrderId(environment + OrderTypeEnum.SKU.getCode() + "-" + skuOrderId);
                    orderResult.setTotalPrice(skuOrder.getTotalPrice());
                    orderResult.setPayPrice(skuOrder.getPayPrice());
                    orderResult.setIntegral(skuOrder.getIntegral());
                    orderResult.setIntegralPrice(skuOrder.getIntegralPrice());
                    orderResult.setOrderType(skuOrder.getType());
                    orderResult.setSkuNames(skuNames);
                    SkuOrder updateSkuOrder = new SkuOrder();
                    updateSkuOrder.setId(skuOrderId);
                    updateSkuOrder.setType(OrderTypeEnum.CAR.getCode().equals(skuOrder.getType()) ? OrderTypeEnum.SKU.getCode() : skuOrder.getType());
                    updateSkuOrder.setBuyWay(OrderTypeEnum.CAR.getCode().equals(skuOrder.getType()) ? OrderTypeEnum.SKU.getCode() : skuOrder.getType());
                    skuOrderDao.updateById(updateSkuOrder);
                    totalPrice = skuOrder.getTotalPrice();
                    totalPayPrice = skuOrder.getPayPrice();
                    SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
                    skuOrderDetailQuery.setSkuOrderId(skuOrderId);
                    List<SkuOrderDetail> list = skuOrderDetailDao.list(skuOrderDetailQuery);
                    for (SkuOrderDetail skuOrderDetail : list) {
                        if (DeliveryWayEnum.FULLREDUCTION.getCode().equals(skuOrderDetail.getDeliveryWay())) {
                            fullReductionPrice += skuOrderDetail.getPayPrice();
                        }
                    }
                } else {
                    PlatformSystemDeploy platformSystemDeploy = jfPlatformSystemDeploy();
                    SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
                    skuOrderDetailQuery.setSkuOrderId(skuOrderId);
                    List<SkuOrderDetail> list = skuOrderDetailDao.list(skuOrderDetailQuery);
                    for (SkuOrderDetail skuOrderDetail : list) {
                        Integer integer = integralPrice > skuOrderDetail.getIntegral() ? skuOrderDetail.getIntegral() : integralPrice;
                        totalPrice += skuOrderDetail.getPrice() * skuOrderDetail.getCount();
                        totalIntegral += integer;
                        double doubleValue = new BigDecimal(integer).divide(new BigDecimal(Integer.parseInt(platformSystemDeploy.getUnit())))
                                .multiply(new BigDecimal(platformSystemDeploy.getDetails())).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                        SkuOrderDetail updateSkuOrderDetail = new SkuOrderDetail();
                        updateSkuOrderDetail.setId(skuOrderDetail.getId());
                        updateSkuOrderDetail.setPayPrice(skuOrderDetail.getPrice() * skuOrderDetail.getCount() - doubleValue);
                        updateSkuOrderDetail.setIntegral(integer);
                        skuOrderDetailDao.updateById(updateSkuOrderDetail);
                        SkuOrderDetail skuOrderDetail1 = new SkuOrderDetail();
                        skuOrderDetail1.setId(skuOrderDetail.getId());
                        skuOrderDetail1.setPayPrice(skuOrderDetail.getPrice() * skuOrderDetail.getCount() - doubleValue);
                        skuOrderDetail1.setIntegral(integer);
                        skuOrderDetailLists.add(skuOrderDetail1);
                        if (DeliveryWayEnum.FULLREDUCTION.getCode().equals(skuOrderDetail.getDeliveryWay())) {
                            fullReductionPrice += skuOrderDetail1.getPayPrice();
                        }
                    }
                    SkuOrder updateSkuOrder = new SkuOrder();
                    updateSkuOrder.setId(skuOrderId);
                    updateSkuOrder.setTotalPrice(totalPrice);
                    double integerPrice = 0.0;
                    Integer integer = 0;
                    if (integralPrice > 0) {
                        integer = integralPrice > totalIntegral ? totalIntegral : integralPrice;
                        integerPrice = new BigDecimal(integer).divide(new BigDecimal(Integer.parseInt(platformSystemDeploy.getUnit())))
                                .multiply(new BigDecimal(platformSystemDeploy.getDetails())).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                    }
                    totalPayPrice = new BigDecimal(totalPrice + "").subtract(new BigDecimal(integerPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                    updateSkuOrder.setPayPrice(totalPayPrice);
                    updateSkuOrder.setIntegralPrice(integerPrice);
                    updateSkuOrder.setIntegral(integer);
                    updateSkuOrder.setType(OrderTypeEnum.CAR.getCode().equals(skuOrder.getType()) ? OrderTypeEnum.SKU.getCode() : skuOrder.getType());
                    updateSkuOrder.setBuyWay(OrderTypeEnum.CAR.getCode().equals(skuOrder.getType()) ? OrderTypeEnum.SKU.getCode() : skuOrder.getType());
                    skuOrderDao.updateById(updateSkuOrder);
                    if (SkuOrderTypeEnum.PERIODIZATION.getCode().equals(skuOrder.getOrderType())) {
                        orderResult.setOutOrderId(environment + OrderTypeEnum.PERIODIZATION.getCode() + "-" + skuOrderId);
                    } else {
                        orderResult.setOutOrderId(environment + OrderTypeEnum.SKU.getCode() + "-" + skuOrderId);
                    }
                    orderResult.setTotalPrice(totalPrice);
                    orderResult.setPayPrice(totalPayPrice);
                    orderResult.setIntegral(integer);
                    orderResult.setIntegralPrice(integerPrice);
                    orderResult.setOrderType(skuOrder.getType());
                    orderResult.setSkuNames(skuNames);
                }
                Double freight = 0.0;
                if (fullReductionPrice > 0.0) {
                    UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
                    urbanFullReductionQuery.setCityId(cityId);
                    UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
                    if (urbanFullReductionDaoFirst == null) {
                        urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                        urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
                    }
                    if (fullReductionPrice < urbanFullReductionDaoFirst.getMoney()) {
                        freight = urbanFullReductionDaoFirst.getFreight();
                        SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
                        skuOrderDeliveryDemand.setLogistics(DeliveryWayEnum.FULLREDUCTION.getCode());
                        skuOrderDeliveryDemand.setSkuOrderId(skuOrderId);
                        skuOrderDeliveryDemand.setPostage(freight);
                        skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.WAITING.getCode());
                        skuOrderDeliveryDemandDao.updateBySkuOrderId(skuOrderDeliveryDemand);
                    }

                }
                orderResult.setPayPrice(totalPayPrice + freight);
                orderResult.setTotalPrice(totalPrice + freight);
                Order order = new Order();
                order.setId(skuOrder.getOrderId());
                order.setMerchantCityId(merchantCityId);
                order.setReceiver(merchantCity.getReceiver());
                order.setReceiverMobile(merchantCity.getReceiverMobile());
                order.setAddress(merchantCity.getProvinceName() + merchantCity.getCityName() + merchantCity.getAreaName() + merchantCity.getAddress());
                orderDao.updateById(order);
            } else {
                orderResult.setOutOrderId(environment + SkuOrderTypeEnum.ENJOY.getCode() + "-" + skuOrderId);
                orderResult.setTotalPrice(skuOrder.getTotalPrice());
                orderResult.setPayPrice(skuOrder.getPayPrice());
                orderResult.setIntegral(skuOrder.getIntegral());
                orderResult.setIntegralPrice(skuOrder.getIntegralPrice());
                orderResult.setOrderType(skuOrder.getType());
                orderResult.setSkuNames(skuNames);
                SkuOrderDetailQuery param = new SkuOrderDetailQuery();
                param.setSkuOrderId(skuOrder.getId());
                List<SkuOrderDetail> skuOrderDetailList = skuOrderDetailDao.list(param);
                for (SkuOrderDetail skuOrderDetail : skuOrderDetailList) {
                    Sku sku = skuDao.findById(skuOrderDetail.getSkuId());
                    RegionalSku regionalSku = regionalSkuDao.findBySkuId(sku.getId());
                    if (regionalSku != null) {
                        if ("N".equals(isBalance) && "Y".equals(regionalSku.getIsMembersExclusive())) {
                            throw new BusinessException(ExceptionEnum.ERROR_1713.getCode(), sku.getTitle() + "," + ExceptionEnum.ERROR_1713.getMessage());
                        }
                    }
                    skuNames.add(sku.getTitle());
                    SkuOrderDeliveryDemandQuery skuOrderDeliveryDemandQuery = new SkuOrderDeliveryDemandQuery();
                    skuOrderDeliveryDemandQuery.setLogistics(DeliveryWayEnum.FULLREDUCTION.getCode());
                    skuOrderDeliveryDemandQuery.setSkuOrderId(skuOrderDetail.getSkuOrderId());
                    skuOrderDeliveryDemandQuery.setNoPostageStatus(SkuOrderStatusEnum.CANCEL.getCode());
                    SkuOrderDeliveryDemand skuOrderDeliveryDemand = skuOrderDeliveryDemandDao.findFirst(skuOrderDeliveryDemandQuery);
                    if (skuOrderDeliveryDemand != null) {
                        orderResult.setPayPrice(skuOrder.getPayPrice() + skuOrderDeliveryDemand.getPostage());
                    }
                }
            }
        }
        SkuOrderDetailQuery param = new SkuOrderDetailQuery();
        param.setSkuOrderId(skuOrderId);
        List<SkuOrderDetail> finalSkuOrderDetailLists = skuOrderDetailDao.list(param);
        //添加分佣信息
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    logger.info("继续支付进来了");
                    Integer fengyongMerchantId = null;
                    Double fengyongProportion = 0.0;
                    Double fengxiaoProportion = null;
                    DailiMerchantQuery param = new DailiMerchantQuery();
                    param.setMobile(merchant.getMobile());
                    param.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
                    param.setIsEnable("Y");
                    DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(param);
                    if (dailiMerchant == null) {
                        throw BusinessException.build(ExceptionEnum.ERROR_1902);
                    }
                    if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(dailiMerchant.getRole())) {
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        fengxiaoProportion = dailiMerchant.getProportion();
                        fengyongMerchantId = dailiMerchant.getPid();
                    } else if (DailiMerchantRoleEnum.MERCHANT.getCode().equals(dailiMerchant.getRole())) {
                        fengyongMerchantId = Integer.parseInt(dailiMerchant.getPidPath().split(",")[0]);
                        DailiMerchant secondMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
                        if (!"Y".equals(secondMerchant.getIsEnable())) {
                            throw BusinessException.build(ExceptionEnum.ERROR_1902);
                        }
                        if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(secondMerchant.getRole())) {
                            DailiMerchant thirdMerchant = dailiMerchantDao.findById(secondMerchant.getPid());
                            if (!"Y".equals(thirdMerchant.getIsEnable())) {
                                throw BusinessException.build(ExceptionEnum.ERROR_1902);
                            }
                            fengxiaoProportion = secondMerchant.getProportion();
                        }
                    } else {
                        fengyongMerchantId = dailiMerchant.getId();
                    }
                    logger.info("skuOrderDetailLists====" + JSONObject.toJSONString(finalSkuOrderDetailLists));
                    if (finalSkuOrderDetailLists.size() > 0) {
                        for (SkuOrderDetail skuOrderDetail : finalSkuOrderDetailLists) {
                            DailiMerchantSkuQuery dailiMerchantSkuQuery = new DailiMerchantSkuQuery();
                            dailiMerchantSkuQuery.setDailiMerchantId(fengyongMerchantId);
                            dailiMerchantSkuQuery.setSkuId(skuOrderDetail.getSkuId());
                            DailiMerchantSku dailiMerchantSku = dailiMerchantSkuDao.findFirst(dailiMerchantSkuQuery);
                            if (dailiMerchantSku == null) {
                                logger.info("购物车下单分佣商品不存在," + dailiMerchantSku.getSkuId());
                                continue;
                            }
                            fengyongProportion = dailiMerchantSku.getProportion();
                            DailiOrderQuery dailiOrderQuery = new DailiOrderQuery();
                            dailiOrderQuery.setOrderId(skuOrderDetail.getId());
                            DailiOrder dailiOrder = dailiOrderDao.findFirst(dailiOrderQuery);
                            if (dailiOrder == null) {
                                continue;
                            }
                            DailiOrder update = new DailiOrder();
                            double fengyongAmount = new BigDecimal(skuOrderDetail.getPayPrice() + "").multiply(new BigDecimal(fengyongProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                            if ("Y".equals(skuOrderDetail.getIsModifyPrice())) {
                                fengyongAmount = new BigDecimal(skuOrderDetail.getModifyPrice() + "").multiply(new BigDecimal(fengyongProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                                update.setPayAmount(skuOrderDetail.getModifyPrice());
                            }
                            update.setFengyongAmount(fengyongAmount);
                            if (fengxiaoProportion != null) {
                                double fenxiaoyuanAmount = new BigDecimal(fengyongAmount + "").multiply(new BigDecimal(fengxiaoProportion + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                                update.setFengxiaoyuanAmount(fenxiaoyuanAmount);
                                update.setFengyongAmount(new BigDecimal(fengyongAmount + "").subtract(new BigDecimal(fenxiaoyuanAmount + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
                            }
                            update.setId(dailiOrder.getId());
                            dailiOrderDao.updateById(update);
                        }
                    }
                } catch (BusinessException e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("#tongliSignContract# error" + e);
                }
            }
        });
        return orderResult;
    }

    @Override
    public OrderResult logisticsPay(Integer merchantId, Integer skuOrderDeliveryDemandId) throws BusinessException {
        OrderResult orderResult = new OrderResult();
        SkuOrderDeliveryDemand skuOrderDeliveryDemand = skuOrderDeliveryDemandDao.findByMerchantIdAndId(merchantId, skuOrderDeliveryDemandId);
        ValidateBusinessException.assertNonNull(skuOrderDeliveryDemand, ExceptionEnum.ERROR_1801);
        ValidateBusinessException.assertFalse(SkuOrderStatusEnum.PAY.getCode().equals(skuOrderDeliveryDemand.getPostageStatus()), ExceptionEnum.ERROR_1801);
        orderResult.setOutOrderId(environment + OrderTypeEnum.LOGISTICS.getCode() + "-" + skuOrderDeliveryDemand.getId());
        orderResult.setOrderType(OrderTypeEnum.LOGISTICS.getCode());
        orderResult.setTotalPrice(skuOrderDeliveryDemand.getPostage());
        orderResult.setPayPrice(skuOrderDeliveryDemand.getPostage());
        return orderResult;
    }

    @Override
    public WeiXinPushResult setDeliveryDemand(SkuOrderDeliveryDemandResult skuOrderDeliveryDemandResult) throws BusinessException {
        WeiXinPushResult weiXinPushResult = new WeiXinPushResult();
        if (skuOrderDeliveryDemandResult.getPostageId() != null) {
            SkuOrderDeliveryDemand skuOrderDeliveryDemand = skuOrderDeliveryDemandDao.findById(skuOrderDeliveryDemandResult.getPostageId());
            ValidateBusinessException.assertNonNull(skuOrderDeliveryDemand, ExceptionEnum.ERROR_1802);
            Merchant merchant = merchantDao.findById(skuOrderDeliveryDemand.getMerchantId());
            SkuOrderDetail skuOrderDetail = skuOrderDetailDao.findById(skuOrderDeliveryDemandResult.getSkuOrderDetailId());
            ValidateBusinessException.assertNonNull(skuOrderDetail, ExceptionEnum.ERROR_1801);
            SkuContent skuContent = skuContentDao.findBySkuId(skuOrderDetail.getSkuId());
            SkuOrder skuOrder = skuOrderDao.findById(skuOrderDeliveryDemand.getSkuOrderId());
            if ("Y".equals(skuContent.getIsSpellOrder())) {
                if (SkuOrderStatusEnum.WAITING.getCode().equals(skuOrder.getPartStatus())) {
                    throw new BusinessException(ExceptionEnum.ERROR_1858.getCode(), ExceptionEnum.ERROR_1858.getMessage());
                }
            }
            Sku sku = skuDao.findById(skuContent.getSkuId());
            SkuOrderDeliveryDemand updateSkuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
            updateSkuOrderDeliveryDemand.setId(skuOrderDeliveryDemandResult.getPostageId());
            if (!SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrder.getOrderType())) {
                updateSkuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.SUCCESS.getCode());
            }
            updateSkuOrderDeliveryDemand.setLogisticsName(skuOrderDeliveryDemandResult.getLogisticsName());
            updateSkuOrderDeliveryDemand.setLogisticsNumber(skuOrderDeliveryDemandResult.getLogisticsNumber());
            skuOrderDeliveryDemandDao.updateById(updateSkuOrderDeliveryDemand);
            SkuOrder param = new SkuOrder();
            param.setId(skuOrderDetail.getSkuOrderId());
            param.setStatus(InquireOrderStatusEnum.DELIVER.getCode());
            param.setDeliveryTime(new Date());
            skuOrderDao.updateById(param);
            weiXinPushResult.setOpenId(merchant.getGzhOpenId());
            weiXinPushResult.setInquireOrderId(skuOrderDeliveryDemand.getSkuOrderId());
            weiXinPushResult.setSkuName(sku.getTitle());
            weiXinPushResult.setStatus(InquireOrderStatusEnum.DELIVER.getName());
            weiXinPushResult.setCreateTime(new Date());
        } else {
            ValidateBusinessException.assertIdNotNull(skuOrderDeliveryDemandResult.getSkuOrderDetailId(), ExceptionEnum.ERROR_1808);
            SkuOrderDetail skuOrderDetail = skuOrderDetailDao.findById(skuOrderDeliveryDemandResult.getSkuOrderDetailId());
            ValidateBusinessException.assertNonNull(skuOrderDetail, ExceptionEnum.ERROR_1801);
            ValidateBusinessException.assertTrue((DeliveryWayEnum.FULLREDUCTION.getCode().equals(skuOrderDetail.getDeliveryWay()) || DeliveryWayEnum.PAYONARRIVAL.getCode().equals(skuOrderDetail.getDeliveryWay()) || DeliveryWayEnum.FREESHIPPING.getCode().equals(skuOrderDetail.getDeliveryWay())), ExceptionEnum.ERROR_1809);
            Merchant merchant = merchantDao.findById(skuOrderDetail.getMerchantId());
            SkuContent skuContent = skuContentDao.findBySkuId(skuOrderDetail.getSkuId());
            if ("Y".equals(skuContent.getIsSpellOrder())) {
                SkuOrder skuOrder = skuOrderDao.findById(skuOrderDetail.getSkuOrderId());
                if (SkuOrderStatusEnum.WAITING.getCode().equals(skuOrder.getPartStatus())) {
                    throw new BusinessException(ExceptionEnum.ERROR_1858.getCode(), ExceptionEnum.ERROR_1858.getMessage());
                }
            }
            Sku sku = skuDao.findById(skuContent.getSkuId());
            SkuOrderDeliveryDemand insertSkuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
            insertSkuOrderDeliveryDemand.setSkuOrderId(skuOrderDetail.getSkuOrderId());
            insertSkuOrderDeliveryDemand.setMerchantId(skuOrderDetail.getMerchantId());
            insertSkuOrderDeliveryDemand.setPostage(0.0);
            insertSkuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.SUCCESS.getCode());
            insertSkuOrderDeliveryDemand.setPostagePayTime(new Date());
            insertSkuOrderDeliveryDemand.setLogisticsName(skuOrderDeliveryDemandResult.getLogisticsName());
            insertSkuOrderDeliveryDemand.setLogisticsNumber(skuOrderDeliveryDemandResult.getLogisticsNumber());
            insertSkuOrderDeliveryDemand.setCreateTime(new Date());
            skuOrderDeliveryDemandDao.insert(insertSkuOrderDeliveryDemand);
            SkuOrder param = new SkuOrder();
            param.setId(insertSkuOrderDeliveryDemand.getSkuOrderId());
            param.setStatus(InquireOrderStatusEnum.DELIVER.getCode());
            param.setDeliveryTime(new Date());
            skuOrderDao.updateById(param);
            weiXinPushResult.setOpenId(merchant.getGzhOpenId());
            weiXinPushResult.setInquireOrderId(skuOrderDetail.getSkuOrderId());
            weiXinPushResult.setSkuName(sku.getTitle());
            weiXinPushResult.setStatus(InquireOrderStatusEnum.DELIVER.getName());
            weiXinPushResult.setCreateTime(new Date());
        }
        return weiXinPushResult;
    }


    @Override
    public WeiXinPushResult setPostage(SkuOrderDeliveryDemandResult skuOrderDeliveryDemandResult) throws BusinessException {
        WeiXinPushResult weiXinPushResult = new WeiXinPushResult();
        Integer skuOrderDetailId = skuOrderDeliveryDemandResult.getSkuOrderDetailId();
        ValidateBusinessException.assertIdNotNull(skuOrderDetailId, ExceptionEnum.ERROR_1808);
        SkuOrderDetail skuOrderDetail = skuOrderDetailDao.findById(skuOrderDetailId);
        ValidateBusinessException.assertNonNull(skuOrderDetail, ExceptionEnum.ERROR_1801);
        ValidateBusinessException.assertTrue(DeliveryWayEnum.PAYMENT.getCode().equals(skuOrderDetail.getDeliveryWay()), ExceptionEnum.ERROR_1810);
        Merchant merchant = merchantDao.findById(skuOrderDetail.getMerchantId());
        Sku sku = skuDao.findById(skuOrderDetail.getSkuId());
        SkuContent skuContent = skuContentDao.findBySkuId(skuOrderDetail.getSkuId());
        SkuOrderDeliveryDemandQuery param = new SkuOrderDeliveryDemandQuery();
        param.setSkuOrderDetailId(skuOrderDetailId);
        param.setNoPostageStatus(SkuOrderStatusEnum.CANCEL.getCode());
        SkuOrderDeliveryDemand skuOrderDeliveryDemand = skuOrderDeliveryDemandDao.findFirst(param);
        ValidateBusinessException.assertNull(skuOrderDeliveryDemand, ExceptionEnum.ERROR_1807);
        SkuOrderDeliveryDemand insertSkuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
        insertSkuOrderDeliveryDemand.setSkuOrderId(skuOrderDetail.getSkuOrderId());
        insertSkuOrderDeliveryDemand.setMerchantId(skuOrderDetail.getMerchantId());
        insertSkuOrderDeliveryDemand.setLogisticsName(skuOrderDeliveryDemandResult.getLogisticsName());
        insertSkuOrderDeliveryDemand.setPostage(skuOrderDeliveryDemandResult.getPostage());
        insertSkuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.WAITING.getCode());
        insertSkuOrderDeliveryDemand.setCreateTime(new Date());
        insertSkuOrderDeliveryDemand.setLogistics(skuContent.getLogistics());
        skuOrderDeliveryDemandDao.insert(insertSkuOrderDeliveryDemand);
        weiXinPushResult.setOpenId(merchant.getGzhOpenId());
        weiXinPushResult.setInquireOrderId(skuOrderDetail.getSkuOrderId());
        weiXinPushResult.setSkuName(sku.getTitle());
        weiXinPushResult.setStatus(SkuOrderStatusEnum.WAITDELIVER.getName());
        weiXinPushResult.setCreateTime(new Date());
        return weiXinPushResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SkuApplyOrderResult examineRefund(Integer supplierId, Integer skuOrderDetailId, String status, String refuseRefundReason, String type) throws BusinessException {
        SkuApplyOrderResult skuApplyOrderResult = new SkuApplyOrderResult();
        WeiXinPushResult weiXinPushResult = new WeiXinPushResult();
        Integer examineId = null;
        String name = null;
        if ("paltform".equals(type)) {
            Platform platform = platformDao.findById(supplierId);
            ValidateBusinessException.assertNonNull(platform, ExceptionEnum.ERROR_1306);
            examineId = platform.getId();
            name = platform.getName();
        } else if ("supplier".equals(type)) {
            Supplier supplier = supplierDao.findById(supplierId);
            ValidateBusinessException.assertNonNull(supplier, ExceptionEnum.ERROR_1511);
            examineId = supplier.getId();
            name = supplier.getName();
        }
        Integer integer = 0;
        SkuOrderDetail skuOrderDetail = skuOrderDetailDao.findById(skuOrderDetailId);
        ValidateBusinessException.assertTrue(SkuOrderStatusEnum.APPLYING.getCode().equals(skuOrderDetail.getApplyRefundStatus()), ExceptionEnum.ERROR_1805);
        ValidateBusinessException.assertTrue(SkuOrderStatusEnum.PASS.getCode().equals(status) || SkuOrderStatusEnum.REFUSE.getCode().equals(status), ExceptionEnum.ERROR_1806);
        SkuOrder skuOrder = skuOrderDao.findById(skuOrderDetail.getSkuOrderId());
        Merchant merchant = merchantDao.findById(skuOrderDetail.getMerchantId());
        Sku sku = skuDao.findByIdAndDelete(skuOrderDetail.getSkuId());
        SkuOrderDetail updateSkuOrderDetail = new SkuOrderDetail();
        updateSkuOrderDetail.setId(skuOrderDetailId);
        if (SkuOrderStatusEnum.PASS.getCode().equals(status) && skuOrderDetail.getPayPrice() <= 0.0) {
            updateSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.APPLYSUCCESS.getCode());
        } else {
            updateSkuOrderDetail.setApplyRefundStatus(status);
        }
        updateSkuOrderDetail.setRefuseRefundReason(refuseRefundReason);
        updateSkuOrderDetail.setRefundTime(new Date());
        updateSkuOrderDetail.setExamineId(examineId);
        updateSkuOrderDetail.setExamineName(name);
        updateSkuOrderDetail.setExamineTime(new Date());
        skuOrderDetailDao.updateById(updateSkuOrderDetail);
        skuApplyOrderResult.setAppletType(skuOrder.getAppletType());
        skuApplyOrderResult.setStatus(status);
        skuApplyOrderResult.setTotalFee(0.0);
        if (SkuOrderTypeEnum.BUY.getCode().equals(skuOrder.getOrderType()) && SkuOrderStatusEnum.PASS.getCode().equals(status)) {
            if (skuOrderDetail.getPayPrice() > 0.0) {
                //调用微信退款
                String outOrderId = environment + OrderTypeEnum.SKU.getCode() + "-" + skuOrder.getId();
                if (SkuOrderBuyTypeEnum.CAR.getCode().equals(skuOrder.getBuyWay())) {
                    outOrderId = environment + OrderTypeEnum.CAR.getCode() + "-" + skuOrder.getOrderId();
                }
                PayOrderQuery param = new PayOrderQuery();
                param.setOutOrderId(outOrderId);
                PayOrder payOrder = payOrderDao.findFirst(param);
                ValidateBusinessException.assertNonNull(payOrder, ExceptionEnum.ERROR_1801);
                ValidateBusinessException.assertStringNotBlank(payOrder.getBillNo(), ExceptionEnum.ERROR_1855);
                PayOrder insertPayOrder = new PayOrder();
                insertPayOrder.setTitle("退款");
                insertPayOrder.setMoney(payOrder.getMoney());
                insertPayOrder.setOutOrderId(environment + OrderTypeEnum.SKU.getCode() + "refund-" + skuOrderDetail.getId());
                insertPayOrder.setMerchantId(skuOrderDetail.getMerchantId());
                insertPayOrder.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
                insertPayOrder.setIsPay("N");
                insertPayOrder.setCreateTime(new Date());
                payOrderDao.insert(insertPayOrder);
                skuApplyOrderResult.setBillNo(payOrder.getBillNo());
                skuApplyOrderResult.setTotalFee(payOrder.getMoney());
                if ("Y".equals(skuOrderDetail.getIsModifyPrice())) {
                    skuApplyOrderResult.setRefundFee(skuOrderDetail.getModifyPrice());
                } else {
                    skuApplyOrderResult.setRefundFee(skuOrderDetail.getPayPrice());
                }
                skuApplyOrderResult.setRefundNo(environment + OrderTypeEnum.SKU.getCode() + "refund-" + insertPayOrder.getId());
            }
            if (skuOrderDetail.getIntegral() != null && skuOrderDetail.getIntegral() > 0) {
                merchantDao.addIntegral(merchant.getId(), skuOrderDetail.getIntegral());
                MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
                merchantIntegralLog.setMerchantId(merchant.getId());
                merchantIntegralLog.setOperation(IntegralOperationEnum.REFUND.getCode());
                merchantIntegralLog.setBeforeIntegral(merchant.getIntegral());
                Merchant afterMerchant = merchantDao.findById(skuOrderDetail.getMerchantId());
                merchantIntegralLog.setAfterIntegral(afterMerchant.getIntegral());
                merchantIntegralLog.setRemarks("退款");
                merchantIntegralLog.setCreateTime(new Date());
                merchantIntegralLogDao.insert(merchantIntegralLog);
                integer = skuOrderDetail.getIntegral();
            }
        } else if (SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrder.getOrderType()) && SkuOrderStatusEnum.PASS.getCode().equals(status)) {
            SkuOrderDetail passSkuOrderDetail = new SkuOrderDetail();
            passSkuOrderDetail.setId(skuOrderDetail.getId());
            passSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.APPLYSUCCESS.getCode());
            passSkuOrderDetail.setRefundTime(new Date());
            skuOrderDetailDao.updateById(passSkuOrderDetail);
            SkuOrder updateSkuOrder = new SkuOrder();
            updateSkuOrder.setStatus(SkuOrderStatusEnum.CANCEL.getCode());
            updateSkuOrder.setId(skuOrderDetail.getSkuOrderId());
            skuOrderDao.updateById(updateSkuOrder);
            if (skuOrderDetail.getIntegral() != null && skuOrderDetail.getIntegral() > 0) {
                merchantDao.addIntegral(merchant.getId(), skuOrderDetail.getIntegral());
                MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
                merchantIntegralLog.setMerchantId(merchant.getId());
                merchantIntegralLog.setOperation(IntegralOperationEnum.REFUND.getCode());
                merchantIntegralLog.setBeforeIntegral(merchant.getIntegral());
                Merchant afterMerchant = merchantDao.findById(skuOrderDetail.getMerchantId());
                merchantIntegralLog.setAfterIntegral(afterMerchant.getIntegral());
                merchantIntegralLog.setRemarks("退款");
                merchantIntegralLog.setCreateTime(new Date());
                merchantIntegralLogDao.insert(merchantIntegralLog);
                integer = skuOrderDetail.getIntegral();
            }
        }else if (SkuOrderTypeEnum.BALANCE.getCode().equals(skuOrder.getOrderType()) && SkuOrderStatusEnum.PASS.getCode().equals(status)) {
            SkuOrderDetail passSkuOrderDetail = new SkuOrderDetail();
            passSkuOrderDetail.setId(skuOrderDetail.getId());
            passSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.APPLYSUCCESS.getCode());
            passSkuOrderDetail.setRefundTime(new Date());
            skuOrderDetailDao.updateById(passSkuOrderDetail);
            if (skuOrderDetail.getIntegral() != null && skuOrderDetail.getIntegral() > 0) {
                merchantDao.addIntegral(merchant.getId(), skuOrderDetail.getIntegral());
                MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
                merchantIntegralLog.setMerchantId(merchant.getId());
                merchantIntegralLog.setOperation(IntegralOperationEnum.REFUND.getCode());
                merchantIntegralLog.setBeforeIntegral(merchant.getIntegral());
                Merchant afterMerchant = merchantDao.findById(skuOrderDetail.getMerchantId());
                merchantIntegralLog.setAfterIntegral(afterMerchant.getIntegral());
                merchantIntegralLog.setRemarks("退款");
                merchantIntegralLog.setCreateTime(new Date());
                merchantIntegralLogDao.insert(merchantIntegralLog);
                integer = skuOrderDetail.getIntegral();
            }
            OrderBalance orderBalance=new OrderBalance();
            orderBalance.setMerchantId(merchant.getId());
            orderBalance.setPayOrderId(skuOrder.getOrderId());
            orderBalance.setBalanceMoney(skuOrderDetail.getPayPrice());
            orderBalance.setRechargeType("refund");
            orderBalance.setNotes("商品退款，订单ID："+skuOrder.getId());
            orderBalance.setStatus("success");
            orderBalance.setCreateTime(new Date());
            orderBalance.setPayTime(new Date());
            orderBalanceDao.insert(orderBalance);
            merchantDao.addBalance(merchant.getId(),skuOrderDetail.getPayPrice());
        }
        weiXinPushResult.setOpenId(merchant.getGzhOpenId());
        weiXinPushResult.setInquireOrderId(skuOrderDetail.getSkuOrderId());
        weiXinPushResult.setSkuName(sku.getTitle());
        weiXinPushResult.setStatus(SkuOrderStatusEnum.getByCode(status).getName());
        weiXinPushResult.setCreateTime(new Date());
        weiXinPushResult.setIntegral(integer);
        weiXinPushResult.setRemark(IntegralOperationEnum.REFUND.getCode());
        skuApplyOrderResult.setInteger(integer);
        skuApplyOrderResult.setWeiXinPushResult(weiXinPushResult);
        return skuApplyOrderResult;
    }

    @Override
    public void examineWaitingCancel(Integer skuOrderId, String status, String refuseRefundReason) throws BusinessException {
        SkuOrder skuOrder = skuOrderDao.findById(skuOrderId);
        Merchant merchant = merchantDao.findById(skuOrder.getMerchantId());
        if (!SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrder.getOrderType())) {
            return;
        }
        if (SkuOrderStatusEnum.PASS.getCode().equals(status)) {
            SkuOrderDetail updateSkuOrderDetail = new SkuOrderDetail();
            updateSkuOrderDetail.setSkuOrderId(skuOrderId);
            updateSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.CANCELSUCCESS.getCode());
            updateSkuOrderDetail.setRefundTime(new Date());
            skuOrderDetailDao.updateBySkuOrderId(updateSkuOrderDetail);
            SkuOrder param = new SkuOrder();
            param.setId(skuOrder.getId());
            param.setStatus(SkuOrderStatusEnum.CANCEL.getCode());
            skuOrderDao.updateById(param);
            merchantDao.addIntegral(skuOrder.getMerchantId(), skuOrder.getIntegral());
            MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
            merchantIntegralLog.setMerchantId(skuOrder.getMerchantId());
            merchantIntegralLog.setOperation(IntegralOperationEnum.REFUND.getCode());
            merchantIntegralLog.setBeforeIntegral(merchant.getIntegral());
            Merchant afterMerchant = merchantDao.findById(skuOrder.getMerchantId());
            merchantIntegralLog.setAfterIntegral(afterMerchant.getIntegral());
            merchantIntegralLog.setRemarks("先享后附取消");
            merchantIntegralLog.setCreateTime(new Date());
            merchantIntegralLogDao.insert(merchantIntegralLog);
        } else {
            SkuOrderDetail updateSkuOrderDetail = new SkuOrderDetail();
            updateSkuOrderDetail.setSkuOrderId(skuOrderId);
            updateSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.CANCELREFUSE.getCode());
            updateSkuOrderDetail.setApplyRefundReason(refuseRefundReason);
            skuOrderDetailDao.updateBySkuOrderId(updateSkuOrderDetail);
            SkuOrder param = new SkuOrder();
            param.setId(skuOrder.getId());
            param.setStatus(SkuOrderStatusEnum.PAY.getCode());
            skuOrderDao.updateById(param);
        }
    }


    @Override
    public SkuApplyOrderResult examineRefundByDirect(Integer supplierId, Integer skuOrderDetailId, String refuseRefundReason, String type, Integer firstSupplierId) throws BusinessException {
        SkuApplyOrderResult skuApplyOrderResult = new SkuApplyOrderResult();
        WeiXinPushResult weiXinPushResult = new WeiXinPushResult();
        Integer examineId = null;
        String name = null;
        if ("paltform".equals(type)) {
            Platform platform = platformDao.findById(supplierId);
            ValidateBusinessException.assertNonNull(platform, ExceptionEnum.ERROR_1306);
            examineId = platform.getId();
            name = platform.getName();
        } else if ("supplier".equals(type)) {
            Supplier supplier = supplierDao.findById(supplierId);
            ValidateBusinessException.assertNonNull(supplier, ExceptionEnum.ERROR_1511);
            examineId = supplier.getId();
            name = supplier.getName();
        }
        Integer integer = 0;
        SkuOrderDetail skuOrderDetail = skuOrderDetailDao.findById(skuOrderDetailId);
        SkuOrder skuOrder = skuOrderDao.findById(skuOrderDetail.getSkuOrderId());
        ValidateBusinessException.assertTrue(firstSupplierId.equals(skuOrder.getSupplierId()), ExceptionEnum.ERROR_1815);
        ValidateBusinessException.assertFalse("N".equals(skuOrder.getIsPay()), ExceptionEnum.ERROR_1874);
        Merchant merchant = merchantDao.findById(skuOrderDetail.getMerchantId());
        Sku sku = skuDao.findByIdAndDelete(skuOrderDetail.getSkuId());
        SkuOrderDetail updateSkuOrderDetail = new SkuOrderDetail();
        updateSkuOrderDetail.setId(skuOrderDetailId);
        updateSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.APPLYSUCCESS.getCode());
        updateSkuOrderDetail.setRefuseRefundReason(refuseRefundReason);
        updateSkuOrderDetail.setRefundTime(new Date());
        updateSkuOrderDetail.setExamineId(examineId);
        updateSkuOrderDetail.setExamineName(name);
        updateSkuOrderDetail.setExamineTime(new Date());
        updateSkuOrderDetail.setIsDirectRefund("Y");
        skuOrderDetailDao.updateById(updateSkuOrderDetail);
        skuApplyOrderResult.setAppletType(skuOrder.getAppletType());
        skuApplyOrderResult.setStatus(SkuOrderStatusEnum.PASS.getCode());
        skuApplyOrderResult.setTotalFee(0.0);
        if (SkuOrderTypeEnum.BUY.getCode().equals(skuOrder.getOrderType())) {
            if (skuOrderDetail.getPayPrice() > 0.0) {
                //调用微信退款
                String outOrderId = environment + OrderTypeEnum.SKU.getCode() + "-" + skuOrder.getId();
                if (SkuOrderBuyTypeEnum.CAR.getCode().equals(skuOrder.getBuyWay())) {
                    outOrderId = environment + OrderTypeEnum.CAR.getCode() + "-" + skuOrder.getOrderId();
                }
                PayOrderQuery param = new PayOrderQuery();
                param.setOutOrderId(outOrderId);
                PayOrder payOrder = payOrderDao.findFirst(param);
                ValidateBusinessException.assertNonNull(payOrder, ExceptionEnum.ERROR_1801);
                ValidateBusinessException.assertStringNotBlank(payOrder.getBillNo(), ExceptionEnum.ERROR_1855);
                PayOrder insertPayOrder = new PayOrder();
                insertPayOrder.setTitle("退款");
                insertPayOrder.setMoney(payOrder.getMoney());
                insertPayOrder.setOutOrderId(environment + OrderTypeEnum.SKU.getCode() + "refund-" + skuOrderDetail.getId());
                insertPayOrder.setMerchantId(skuOrderDetail.getMerchantId());
                insertPayOrder.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
                insertPayOrder.setIsPay("N");
                insertPayOrder.setCreateTime(new Date());
                payOrderDao.insert(insertPayOrder);
                skuApplyOrderResult.setBillNo(payOrder.getBillNo());
                skuApplyOrderResult.setTotalFee(payOrder.getMoney());
                if ("Y".equals(skuOrderDetail.getIsModifyPrice())) {
                    skuApplyOrderResult.setRefundFee(skuOrderDetail.getModifyPrice());
                } else {
                    skuApplyOrderResult.setRefundFee(skuOrderDetail.getPayPrice());
                }
                skuApplyOrderResult.setRefundNo(environment + OrderTypeEnum.SKU.getCode() + "refund-" + insertPayOrder.getId());
            }
            if (skuOrderDetail.getIntegral() != null && skuOrderDetail.getIntegral() > 0) {
                merchantDao.addIntegral(merchant.getId(), skuOrderDetail.getIntegral());
                MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
                merchantIntegralLog.setMerchantId(merchant.getId());
                merchantIntegralLog.setOperation(IntegralOperationEnum.REFUND.getCode());
                merchantIntegralLog.setBeforeIntegral(merchant.getIntegral());
                Merchant afterMerchant = merchantDao.findById(skuOrderDetail.getMerchantId());
                merchantIntegralLog.setAfterIntegral(afterMerchant.getIntegral());
                merchantIntegralLog.setRemarks("退款");
                merchantIntegralLog.setCreateTime(new Date());
                merchantIntegralLogDao.insert(merchantIntegralLog);
                integer = skuOrderDetail.getIntegral();
            }
        } else if (SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrder.getOrderType())) {
            SkuOrderDetail passSkuOrderDetail = new SkuOrderDetail();
            passSkuOrderDetail.setId(skuOrderDetail.getId());
            passSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.APPLYSUCCESS.getCode());
            passSkuOrderDetail.setRefundTime(new Date());
            skuOrderDetailDao.updateById(passSkuOrderDetail);
            SkuOrder updateSkuOrder = new SkuOrder();
            updateSkuOrder.setStatus(SkuOrderStatusEnum.CANCEL.getCode());
            updateSkuOrder.setId(skuOrderDetail.getSkuOrderId());
            skuOrderDao.updateById(updateSkuOrder);
            if (skuOrderDetail.getIntegral() != null && skuOrderDetail.getIntegral() > 0) {
                merchantDao.addIntegral(merchant.getId(), skuOrderDetail.getIntegral());
                MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
                merchantIntegralLog.setMerchantId(merchant.getId());
                merchantIntegralLog.setOperation(IntegralOperationEnum.REFUND.getCode());
                merchantIntegralLog.setBeforeIntegral(merchant.getIntegral());
                Merchant afterMerchant = merchantDao.findById(skuOrderDetail.getMerchantId());
                merchantIntegralLog.setAfterIntegral(afterMerchant.getIntegral());
                merchantIntegralLog.setRemarks("退款");
                merchantIntegralLog.setCreateTime(new Date());
                merchantIntegralLogDao.insert(merchantIntegralLog);
                integer = skuOrderDetail.getIntegral();
            }
        }else if (SkuOrderTypeEnum.BALANCE.getCode().equals(skuOrder.getOrderType())) {
            SkuOrderDetail passSkuOrderDetail = new SkuOrderDetail();
            passSkuOrderDetail.setId(skuOrderDetail.getId());
            passSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.APPLYSUCCESS.getCode());
            passSkuOrderDetail.setRefundTime(new Date());
            skuOrderDetailDao.updateById(passSkuOrderDetail);
            if (skuOrderDetail.getIntegral() != null && skuOrderDetail.getIntegral() > 0) {
                merchantDao.addIntegral(merchant.getId(), skuOrderDetail.getIntegral());
                MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
                merchantIntegralLog.setMerchantId(merchant.getId());
                merchantIntegralLog.setOperation(IntegralOperationEnum.REFUND.getCode());
                merchantIntegralLog.setBeforeIntegral(merchant.getIntegral());
                Merchant afterMerchant = merchantDao.findById(skuOrderDetail.getMerchantId());
                merchantIntegralLog.setAfterIntegral(afterMerchant.getIntegral());
                merchantIntegralLog.setRemarks("退款");
                merchantIntegralLog.setCreateTime(new Date());
                merchantIntegralLogDao.insert(merchantIntegralLog);
                integer = skuOrderDetail.getIntegral();
            }
            OrderBalance orderBalance=new OrderBalance();
            orderBalance.setMerchantId(merchant.getId());
            orderBalance.setPayOrderId(skuOrder.getOrderId());
            orderBalance.setBalanceMoney(skuOrderDetail.getPayPrice());
            orderBalance.setRechargeType("refund");
            orderBalance.setNotes("商品退款，订单ID："+skuOrder.getId());
            orderBalance.setStatus("success");
            orderBalance.setCreateTime(new Date());
            orderBalance.setPayTime(new Date());
            orderBalanceDao.insert(orderBalance);
            merchantDao.addBalance(merchant.getId(),skuOrderDetail.getPayPrice());
        }
        weiXinPushResult.setOpenId(merchant.getGzhOpenId());
        weiXinPushResult.setInquireOrderId(skuOrderDetail.getSkuOrderId());
        weiXinPushResult.setSkuName(sku.getTitle());
        weiXinPushResult.setStatus(SkuOrderStatusEnum.PASS.getName());
        weiXinPushResult.setCreateTime(new Date());
        weiXinPushResult.setIntegral(integer);
        weiXinPushResult.setRemark(IntegralOperationEnum.REFUND.getCode());
        skuApplyOrderResult.setInteger(integer);
        skuApplyOrderResult.setWeiXinPushResult(weiXinPushResult);
        return skuApplyOrderResult;
    }


    @Override
    public Page<SkuOrderResult> getOrderListResultList(PlatformOrderListReq req, PagerInfo pr) throws BusinessException {
        Page<SkuOrderResult> page = new Page<>(pr.getStart(), pr.getPageSize());
        Integer orderListResultCount = orderDao.getOrderListResultCount(req);
        page.setTotalPage(orderListResultCount);
        if (orderListResultCount > 0) {
            List<SkuOrderResult> orderListResult = orderDao.getOrderListResult(req, pr.getStart(), pr.getPageSize());
            for (SkuOrderResult skuOrderResult : orderListResult) {
                SkuOrder skuOrder = skuOrderDao.findById(skuOrderResult.getId());
                BeanUtils.copyProperties(skuOrderResult, skuOrder);
                Order order = orderDao.findById(skuOrder.getOrderId());
                skuOrderResult.setAddress(order.getAddress());
                skuOrderResult.setReceiver(order.getReceiver());
                skuOrderResult.setReceiverMobile(order.getReceiverMobile());
                skuOrderResult.setCreateTime(order.getCreateTime());
                skuOrderResult.setMerchantCity(skuOrder.getMerchantCity());
                Supplier supplier = supplierDao.findById(skuOrderResult.getSupplierId());
                if (supplier != null) {
                    skuOrderResult.setSupplierName(supplier.getName());
                }
                SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
                skuOrderDetailQuery.setSkuOrderId(skuOrderResult.getId());
                List<SkuOrderDetail> skuOrderDetails = skuOrderDetailDao.list(skuOrderDetailQuery);
                List<SkuOrderDetailResult> skuOrderDetailResults = DTOUtils.convertList(skuOrderDetails, SkuOrderDetailResult.class);
                skuOrderResult.setSkuOrderDetailResults(skuOrderDetailResults);
                for (SkuOrderDetailResult skuOrderDetailResult : skuOrderDetailResults) {
                    skuOrderDetailResult.setStatus(skuOrderResult.getStatus());
                    Sku sku = skuDao.findById(skuOrderDetailResult.getSkuId());
                    if (sku != null) {
                        skuOrderDetailResult.setSkuName(sku.getTitle());
                    }
                    SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuOrderDetailResult.getSkuSalesInformationId());
                    if (skuSalesInformation != null) {
                        skuOrderDetailResult.setSpecifications(skuSalesInformation.getSpecifications());
                        skuOrderDetailResult.setUnit(skuSalesInformation.getUnit());
                        skuOrderDetailResult.setSkuSalesInformationName(skuSalesInformation.getProductName());
                    }
                    SkuOrderDeliveryDemandQuery skuOrderDeliveryDemandQuery = new SkuOrderDeliveryDemandQuery();
                    skuOrderDeliveryDemandQuery.setSkuOrderDetailId(skuOrderDetailResult.getId());
                    skuOrderDeliveryDemandQuery.setSkuOrderId(skuOrderDetailResult.getSkuOrderId());
                    skuOrderDeliveryDemandQuery.setNoPostageStatus(SkuOrderStatusEnum.CANCEL.getCode());
                    SkuOrderDeliveryDemand skuOrderDeliveryDemand = skuOrderDeliveryDemandDao.findFirst(skuOrderDeliveryDemandQuery);
                    if (skuOrderDeliveryDemand != null) {
                        skuOrderDetailResult.setPostageStatus(skuOrderDeliveryDemand.getPostageStatus());
                        if (DeliveryWayEnum.FULLREDUCTION.getCode().equals(skuOrderDeliveryDemand.getLogistics())) {
                            if (skuOrderDeliveryDemand.getPostage() == 0) {
                                skuOrderDetailResult.setIsFreeShipping("Y");
                            }
                        }
                    }
                }
            }
            page.setData(orderListResult);
        }

        return page;
    }


    @Override
    public List<SkuOrderResultExport> getOrderListResultListExport(PlatformOrderListReq req, PagerInfo pr) throws BusinessException {
        List<SkuOrderResultExport> list = new ArrayList<>();
        Integer orderListResultCount = orderDao.getOrderListResultCount(req);
        if (orderListResultCount > 0) {
            List<SkuOrderResult> orderListResult = orderDao.getOrderListResult(req, pr.getStart(), pr.getPageSize());
            List<SkuOrder> skuOrders = skuOrderDao.listByNew(new SkuOrderQuery());
            Map<Integer, SkuOrder> skuOrderMap = skuOrders.stream().collect(Collectors.toMap(SkuOrder::getId, i -> i, (key1, key2) -> key1));
            List<Order> orderList = orderDao.list(new OrderQuery());
            Map<Integer, Order> orderMap = orderList.stream().collect(Collectors.toMap(Order::getId, i -> i, (key1, key2) -> key1));
            List<Supplier> supplierList = supplierDao.list(new SupplierQuery());
            Map<Integer, Supplier> supplierMap = supplierList.stream().collect(Collectors.toMap(Supplier::getId, i -> i, (key1, key2) -> key1));
            List<SkuOrderDetail> skuOrderDetailList = skuOrderDetailDao.list(new SkuOrderDetailQuery());
            Map<Integer, List<SkuOrderDetail>> skuOrderDetailMap = skuOrderDetailList.stream().collect(Collectors.groupingBy(SkuOrderDetail::getSkuOrderId));
            List<Sku> skuList = skuDao.list(new SkuQuery());
            Map<Integer, Sku> skuMap = skuList.stream().collect(Collectors.toMap(Sku::getId, i -> i, (key1, key2) -> key1));
            List<Merchant> merchantList = merchantDao.list(new MerchantQuery());
            Map<Integer, Merchant> merchantIdMap = merchantList.stream().collect(Collectors.toMap(Merchant::getId, i -> i, (key1, key2) -> key1));
            Map<String, Merchant> merchantMobileMap = merchantList.stream().collect(Collectors.toMap(Merchant::getMobile, i -> i, (key1, key2) -> key1));
            List<DailiMerchant> dailiMerchantList = dailiMerchantDao.list(new DailiMerchantQuery());
            Map<Integer, DailiMerchant> dailiMerchantIdMap = dailiMerchantList.stream().collect(Collectors.toMap(DailiMerchant::getId, i -> i, (key1, key2) -> key1));
            Map<String, DailiMerchant> dailiMerchantMobileMap = dailiMerchantList.stream().collect(Collectors.toMap(DailiMerchant::getMobile, i -> i, (key1, key2) -> key1));
            SkuOrderDeliveryDemandQuery skuOrderDeliveryDemandQuery = new SkuOrderDeliveryDemandQuery();
            skuOrderDeliveryDemandQuery.setNoPostageStatus(SkuOrderStatusEnum.CANCEL.getCode());
            List<SkuOrderDeliveryDemand> skuOrderDeliveryDemandList = skuOrderDeliveryDemandDao.list(skuOrderDeliveryDemandQuery);
            Map<String, SkuOrderDeliveryDemand> skuOrderDeliveryDemandMap = skuOrderDeliveryDemandList.stream().collect(Collectors.toMap(item -> item.getSkuOrderDetailId() + "_" + item.getSkuOrderId(), i -> i, (key1, key2) -> key1));
            List<SkuSalesInformation> skuSalesInformations = skuSalesInformationDao.list(new SkuSalesInformationQuery());
            Map<Integer, SkuSalesInformation> skuSalesInformationMap = skuSalesInformations.stream().collect(Collectors.toMap(SkuSalesInformation::getId, i -> i, (key1, key2) -> key1));
            for (SkuOrderResult skuOrderResult : orderListResult) {
                SkuOrder skuOrder = skuOrderMap.get(skuOrderResult.getId());
                Order order = orderMap.get(skuOrder.getOrderId());
                Supplier supplier = supplierMap.get(skuOrder.getSupplierId());
                List<SkuOrderDetail> skuOrderDetails = skuOrderDetailMap.get(skuOrderResult.getId());
                List<SkuOrderDetailResult> skuOrderDetailResults = DTOUtils.convertList(skuOrderDetails, SkuOrderDetailResult.class);
                for (SkuOrderDetailResult skuOrderDetailResult : skuOrderDetailResults) {
                    SkuOrderResultExport skuOrderResultExport = new SkuOrderResultExport();
                    Sku sku = skuMap.get(skuOrderDetailResult.getSkuId());
                    if (sku != null) {
                        skuOrderDetailResult.setSkuName(sku.getTitle());
                    }
                    SkuOrderDeliveryDemand skuOrderDeliveryDemand = skuOrderDeliveryDemandMap
                            .get(skuOrderDetailResult.getId() + "_" + skuOrderDetailResult.getSkuOrderId());
                    if (skuOrderDeliveryDemand != null) {
                        skuOrderDetailResult.setPostageStatus(skuOrderDeliveryDemand.getPostageStatus());
                    }
                    SkuSalesInformation skuSalesInformation = skuSalesInformationMap.get(skuOrderDetailResult.getSkuSalesInformationId());
                    if (skuSalesInformation != null) {
                        skuOrderDetailResult.setSpecifications(skuSalesInformation.getSpecifications());
                        skuOrderDetailResult.setUnit(skuSalesInformation.getUnit());
                        skuOrderDetailResult.setProductName(skuSalesInformation.getProductName());
                    }
                    BeanUtils.copyProperties(skuOrderResultExport, skuOrderDetailResult);
                    skuOrderResultExport.setStatus(skuOrder.getStatus());
                    skuOrderResultExport.setOrderType(skuOrder.getOrderType());
                    skuOrderResultExport.setReceiver(order.getReceiver());
                    skuOrderResultExport.setReceiverMobile(order.getReceiverMobile());
                    skuOrderResultExport.setAddress(order.getAddress());
                    skuOrderResultExport.setIsPay(skuOrder.getIsPay());
                    skuOrderResultExport.setCreateTime(skuOrder.getCreateTime());
                    skuOrderResultExport.setMerchantCity(skuOrder.getMerchantCity());
                    if (supplier != null) {
                        skuOrderResultExport.setSupplierName(supplier.getName());
                    }
                    skuOrderResultExport.setMerchantId(order.getMerchantId());
                    Merchant merchant = merchantIdMap.get(order.getMerchantId());
                    if (merchant != null) {
                        skuOrderResultExport.setMerchantName(merchant.getName());
                        skuOrderResultExport.setMerchantMobile(merchant.getMobile());
                        DailiMerchant dailiMerchant = dailiMerchantMobileMap.get(merchant.getMobile());
                        if (dailiMerchant != null) {
                            DailiMerchant dailiMerchant1 = dailiMerchantIdMap.get(dailiMerchant.getPid());
                            if (dailiMerchant1 != null) {
                                Merchant merchant1 = merchantMobileMap.get(dailiMerchant1.getMobile());
                                if (merchant1 != null) {
                                    skuOrderResultExport.setPlaceMerchantMobile(merchant1.getMobile());
                                    skuOrderResultExport.setPlaceMerchantName(merchant1.getName());
                                }
                            }
                        }
                    }
                    list.add(skuOrderResultExport);
                }
            }

        }
        return list;
    }

    @Override
    public SkuOrderCountResult getMerchantOrderResult(String status, Integer merchantId, PagerInfo pr) {
        SkuOrderCountResult skuOrderCountResult = new SkuOrderCountResult();
        SkuOrderQuery param = new SkuOrderQuery();
        param.setStatus(SkuOrderStatusEnum.WAITING.getCode());
        param.setMerchantId(merchantId);
        Integer waitCount = skuOrderDao.count(param);
        param.setStatus(SkuOrderStatusEnum.PAY.getCode());
        param.setMerchantId(merchantId);
        Integer waitDeliverCount = skuOrderDao.count(param);
        param.setStatus(SkuOrderStatusEnum.DELIVER.getCode());
        param.setMerchantId(merchantId);
        Integer deliverCount = skuOrderDao.count(param);
        param.setStatus(SkuOrderStatusEnum.SUCCESS.getCode());
        param.setMerchantId(merchantId);
        Integer successCount = skuOrderDao.count(param);
        skuOrderCountResult.setWaitCount(waitCount);
        skuOrderCountResult.setWaitDeliverCount(waitDeliverCount);
        skuOrderCountResult.setDeliverCount(deliverCount);
        skuOrderCountResult.setSuccessCount(successCount);
        Page<SkuOrderResult> page = new Page<>(pr.getStart(), pr.getPageSize());
        param.setStatus(status);
        param.setMerchantId(merchantId);
        Integer count = skuOrderDao.count(param);
        if (SkuOrderStatusEnum.WAITING.getCode().equals(status)) {
            count = skuOrderDao.countByWaiting(param);
        }

        if (count > 0) {
            logger.info("param=====" + JSONObject.toJSONString(param));
            List<SkuOrder> skuOrderList = skuOrderDao.page(param, pr.getStart(), pr.getPageSize());
            logger.info("skuOrderList=====" + JSONObject.toJSONString(skuOrderList));
            if (SkuOrderStatusEnum.WAITING.getCode().equals(status)) {
                skuOrderList = skuOrderDao.pageByWaiting(param, pr.getStart(), pr.getPageSize());
            }
            List<SkuOrderResult> skuOrderResults = DTOUtils.convertList(skuOrderList, SkuOrderResult.class);
            for (SkuOrderResult skuOrderResult : skuOrderResults) {
                Double modifyPrice = 0.0;
                Order order = orderDao.findById(skuOrderResult.getOrderId());
                skuOrderResult.setAddress(order.getAddress());
                skuOrderResult.setMerchantCityId(order.getMerchantCityId());
                SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
                skuOrderDetailQuery.setSkuOrderId(skuOrderResult.getId());
                List<SkuOrderDetail> list = skuOrderDetailDao.list(skuOrderDetailQuery);
                List<SkuOrderDetailResult> skuOrderDetailResults = DTOUtils.convertList(list, SkuOrderDetailResult.class);
                Double postage = 0.0;
                for (SkuOrderDetailResult skuOrderDetailResult : skuOrderDetailResults) {
                    Sku sku = skuDao.findByIdAndDelete(skuOrderDetailResult.getSkuId());
                    if (sku != null) {
                        skuOrderDetailResult.setSkuName(sku.getTitle());
                        SkuContent skuContent = skuContentDao.findBySkuId(skuOrderDetailResult.getSkuId());
                        if (skuContent != null) {
                            skuOrderDetailResult.setCover(skuContent.getCover());
                            skuOrderResult.setSkuOrderDetailResults(skuOrderDetailResults);
                            if ("Y".equals(skuContent.getIsSpellOrder()) && SkuTypeEnum.PART.getCode().equals(skuOrderResult.getType())) {
                                SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
                                skuOrderQuery.setPartSn(skuOrderResult.getPartSn());
                                skuOrderQuery.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
                                Integer scount = skuOrderDao.count(skuOrderQuery);
                                skuOrderResult.setFewpeople(skuContent.getSpellOrderPeople() - scount);
                            }
                        }
                        SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuOrderDetailResult.getSkuSalesInformationId());
                        if (skuSalesInformation != null) {
                            if (StringUtils.isNotBlank(skuSalesInformation.getCover())) {
                                skuOrderDetailResult.setCover(skuSalesInformation.getCover());
                            }
                        }
                        SkuCategory skuCategory = skuCategoryDao.findById(sku.getCategoryId());
                        if (skuCategory != null)
                            skuOrderDetailResult.setCategoryName(skuCategory.getName());
                    }
                    SkuOrderDeliveryDemandQuery skuOrderDeliveryDemandQuery = new SkuOrderDeliveryDemandQuery();
                    skuOrderDeliveryDemandQuery.setSkuOrderId(skuOrderDetailResult.getSkuOrderId());
                    SkuOrderDeliveryDemand skuOrderDeliveryDemand = skuOrderDeliveryDemandDao.findFirst(skuOrderDeliveryDemandQuery);
                    if (skuOrderDeliveryDemand != null) {
                        SkuOrderDeliveryDemandResult skuOrderDeliveryDemandResult = new SkuOrderDeliveryDemandResult();
                        BeanUtils.copyProperties(skuOrderDeliveryDemandResult, skuOrderDeliveryDemand);
                        skuOrderResult.setSkuOrderDeliveryDemandResult(skuOrderDeliveryDemandResult);
                        if (DeliveryWayEnum.FULLREDUCTION.getCode().equals(skuOrderDeliveryDemand.getLogistics())) {
                            postage = skuOrderDeliveryDemand.getPostage();
                        }
                    }
                    if ("Y".equals(skuOrderDetailResult.getIsModifyPrice())) {
                        modifyPrice += skuOrderDetailResult.getModifyPrice();
                    } else {
                        modifyPrice += skuOrderDetailResult.getPayPrice();
                    }
                }
                if ("Y".equals(skuOrderResult.getIsModifyPrice())) {
                    skuOrderResult.setModifyPrice(modifyPrice);
                }
                skuOrderResult.setPayPrice(skuOrderResult.getPayPrice() + postage);
                if (!SkuOrderStatusEnum.CANCEL.getCode().equals(skuOrderResult.getStatus()) && "N".equals(skuOrderResult.getIsPay())) {
                    PlatformSystemDeploy platformSystemDeploy = getPlatformSystemDeploy(SkuTypeEnum.SKU.getCode(), SkuOrderStatusEnum.WAITING.getCode());
                    if (platformSystemDeploy != null && SkuOrderTypeEnum.BUY.getCode().equals(skuOrderResult.getOrderType())) {
                        skuOrderResult.setExpireTime(getWebExpireTime(platformSystemDeploy.getUnit(), platformSystemDeploy.getDetails().intValue(), order.getCreateTime()));
                    }
                    if (SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrderResult.getOrderType())) {
                        skuOrderResult.setExpireTime(getEnjoyEndTime(skuOrderResult.getCreateTime()));
                    }
                }
                if (SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrderResult.getOrderType())
                        && SkuOrderStatusEnum.SUCCESS.getCode().equals(skuOrderResult.getStatus()) && "N".equals(skuOrderResult.getIsPay())) {
                    skuOrderResult.setStatus(SkuOrderStatusEnum.WAITING.getCode());
                }
            }
            page.setData(skuOrderResults);
            skuOrderCountResult.setSkuOrderResultPage(page);
        }
        return skuOrderCountResult;
    }

    @Override
    public List<SkuOrderResult> getMerchantOrderResultByNoSuccess(Integer merchantId) {
        SkuOrderQuery param = new SkuOrderQuery();
        param.setNoStatus(SkuOrderStatusEnum.SUCCESS.getCode());
        param.setReverseStatus(SkuOrderStatusEnum.CANCEL.getCode());
        param.setMerchantId(merchantId);
        Integer count = skuOrderDao.count(param);
        if (count > 0) {
            List<SkuOrder> skuOrderList = skuOrderDao.listBySku(param);
            List<SkuOrderResult> skuOrderResults = DTOUtils.convertList(skuOrderList, SkuOrderResult.class);
            for (SkuOrderResult skuOrderResult : skuOrderResults) {
                SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
                skuOrderDetailQuery.setSkuOrderId(skuOrderResult.getId());
                List<SkuOrderDetail> list = skuOrderDetailDao.list(skuOrderDetailQuery);
                List<SkuOrderDetailResult> skuOrderDetailResults = DTOUtils.convertList(list, SkuOrderDetailResult.class);
                for (SkuOrderDetailResult skuOrderDetailResult : skuOrderDetailResults) {
                    Sku sku = skuDao.findByIdAndDelete(skuOrderDetailResult.getSkuId());
                    if (sku != null) {
                        skuOrderResult.setSkuName(sku.getTitle());
                        SkuContent skuContent = skuContentDao.findBySkuId(skuOrderDetailResult.getSkuId());
                        if (skuContent != null) {
                            skuOrderResult.setCover(skuContent.getCover());
                        }
                        SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuOrderDetailResult.getSkuSalesInformationId());
                        if (skuSalesInformation != null) {
                            if (StringUtils.isNotBlank(skuSalesInformation.getCover())) {
                                skuOrderResult.setCover(skuSalesInformation.getCover());
                            }
                        }
                    }
                }
            }
            return skuOrderResults;
        }
        return null;
    }


    @Override
    public Page<SkuOrderResult> getMerchantOrderResultByPeriodization(Integer merchantId, PagerInfo pagerInfo) {
        Page<SkuOrderResult> page = new Page<>(pagerInfo.getPageIndex(), pagerInfo.getPageSize());
        OrderQuery param = new OrderQuery();
        param.setType(SkuSalesInformationTypeEnum.PERIODIZATION.getCode());
        param.setMerchantId(merchantId);
        Integer count = orderDao.count(param);
        page.setTotalPage(count);
        if (count > 0) {
            List<Order> orders = orderDao.page(param, pagerInfo.getStart(), pagerInfo.getPageSize());
            List<SkuOrderResult> skuOrderResults = DTOUtils.convertList(orders, SkuOrderResult.class);
            for (SkuOrderResult skuOrderResult : skuOrderResults) {
                skuOrderResult.setOrderId(skuOrderResult.getId());
                SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
                skuOrderDetailQuery.setSkuOrderId(skuOrderResult.getId());
                skuOrderDetailQuery.setPeriodsNumber(0);
                List<SkuOrderDetail> list = skuOrderDetailDao.list(skuOrderDetailQuery);
                List<SkuOrderDetailResult> skuOrderDetailResults = DTOUtils.convertList(list, SkuOrderDetailResult.class);
                for (SkuOrderDetailResult skuOrderDetailResult : skuOrderDetailResults) {
                    Sku sku = skuDao.findByIdAndDelete(skuOrderDetailResult.getSkuId());
                    skuOrderDetailResult.setSkuName(sku.getTitle());
                }
                skuOrderResult.setSkuOrderDetailResults(skuOrderDetailResults);
            }

            page.setData(skuOrderResults);
        }
        return page;
    }

    @Override
    public PeriodizationOrderDetailResult getPeriodizationOrderDetailResult(Integer merchantId, Integer orderId) {
        PeriodizationOrderDetailResult periodizationOrderDetailResult = new PeriodizationOrderDetailResult();
        List<PeriodizationOrderResult> periodizationOrderResults = new ArrayList<>();
        List<PeriodizationOrderSkuResult> periodizationOrderSkuResults = new ArrayList<>();
        Order order = orderDao.findById(orderId);
        List<SkuOrder> list = skuOrderDao.getListByOrderId(SkuOrderStatusEnum.SUCCESS.getCode(), orderId);
        String isLast = "N";
        if (order.getPeriodsNumber() == list.size()) {
            isLast = "Y";
        }
        for (int i = 0; i < list.size(); i++) {
            SkuOrder skuOrder = list.get(i);
            PeriodizationOrderSkuResult periodizationOrderSkuResult = new PeriodizationOrderSkuResult();
            SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
            skuOrderDetailQuery.setSkuOrderId(skuOrder.getId());
            List<SkuOrderDetail> skuOrderDetailList = skuOrderDetailDao.list(skuOrderDetailQuery);
            List<SkuOrderDetailResult> skuOrderDetailResults = DTOUtils.convertList(skuOrderDetailList, SkuOrderDetailResult.class);
            for (SkuOrderDetailResult skuOrderDetailResult : skuOrderDetailResults) {
                Sku sku = skuDao.findById(skuOrderDetailResult.getSkuId());
                SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuOrderDetailResult.getSkuSalesInformationId());
                if (sku != null) {
                    SkuContent skuContent = skuContentDao.findBySkuId(sku.getId());
                    skuOrderDetailResult.setCover(skuContent.getCover());
                    skuOrderDetailResult.setSkuName(sku.getTitle());
                    SkuOrderDetailPeriodizationQuery skuOrderDetailPeriodizationQuery = new SkuOrderDetailPeriodizationQuery();
                    skuOrderDetailPeriodizationQuery.setSkuOrderDetailId(skuOrderDetailResult.getId());
                    SkuOrderDetailPeriodization skuOrderDetailPeriodization = skuOrderDetailPeriodizationDao.findFirst(skuOrderDetailPeriodizationQuery);
                    if (skuOrderDetailResult.getPeriodsNumber() + 1 == list.size()) {
                        PeriodizationOrderResult periodizationOrderResult = new PeriodizationOrderResult();
                        periodizationOrderResult.setId(sku.getId());
                        periodizationOrderResult.setSkuSalesInformationId(skuOrderDetailResult.getSkuSalesInformationId());
                        periodizationOrderResult.setTitle(sku.getTitle());
                        periodizationOrderResult.setSubTitle(sku.getSubTitle());
                        periodizationOrderResult.setCount(skuOrderDetailResult.getCount());
                        periodizationOrderResult.setPrice(skuOrderDetailResult.getPrice());
                        periodizationOrderResult.setCover(skuContent.getCover());
                        periodizationOrderResult.setIsLast(isLast);
                        periodizationOrderResult.setStatus(order.getStatus());
                        if (skuSalesInformation != null) {
                            if (StringUtils.isNotBlank(skuSalesInformation.getCover())) {
                                periodizationOrderResult.setCover(skuSalesInformation.getCover());
                            }
                            periodizationOrderResult.setUnit(skuSalesInformation.getUnit());
                            periodizationOrderResult.setProductName(skuSalesInformation.getProductName());
                            periodizationOrderResult.setSpecifications(skuSalesInformation.getSpecifications());
                        }
                        PeriodizationSku periodizationSku = periodizationSkuDao.findBySkuId(sku.getId());
                        if (periodizationSku != null) {
                            periodizationOrderResult.setIsHost("Y");
                        }
                        if (skuOrderDetailPeriodization != null) {
                            periodizationOrderResult.setAverageSpecifications(skuOrderDetailPeriodization.getTotalSpecifications() / order.getPeriodsNumber() + skuSalesInformation.getUnit());
                            periodizationOrderResult.setExtractSpecifications(skuOrderDetailPeriodization.getExtractSpecifications());
                            periodizationOrderResult.setStock(skuOrderDetailPeriodization.getResidueSpecifications());
                        }
                        periodizationOrderResults.add(periodizationOrderResult);
                    }
                    if (skuSalesInformation != null) {
                        skuOrderDetailResult.setUnit(skuSalesInformation.getUnit());
                    }
                    if (skuOrderDetailPeriodization != null) {
                        skuOrderDetailResult.setExtractSpecifications(skuOrderDetailPeriodization.getExtractSpecifications());
                        skuOrderDetailResult.setAverageSpecifications(skuOrderDetailPeriodization.getTotalSpecifications() / order.getPeriodsNumber() + skuSalesInformation.getUnit());
                    }
                }
            }
            periodizationOrderSkuResult.setCreateTime(skuOrder.getCreateTime());
            periodizationOrderSkuResult.setPeriodsNumber(skuOrder.getPeriodsNumber());
            periodizationOrderSkuResult.setId(skuOrder.getId());
            periodizationOrderSkuResult.setTotalPayPrice(skuOrder.getPayPrice());
            periodizationOrderSkuResult.setStatus(skuOrder.getStatus());
            periodizationOrderSkuResult.setSkuOrderDetailResults(skuOrderDetailResults);
            periodizationOrderSkuResults.add(periodizationOrderSkuResult);
        }
        periodizationOrderDetailResult.setPeriodizationOrderResults(periodizationOrderResults.stream().sorted(Comparator.comparing(PeriodizationOrderResult::getIsHost).reversed()).collect(Collectors.toList()));
        periodizationOrderDetailResult.setPeriodizationOrderSkuResults(periodizationOrderSkuResults.stream().sorted(Comparator.comparing(PeriodizationOrderSkuResult::getPeriodsNumber)).collect(Collectors.toList()));
        return periodizationOrderDetailResult;
    }

    @Override
    public EnjoySkuOrderResult getEnjoySkuOrderResult(String date, Integer merchantId, PagerInfo pagerInfo, Integer dailiMerchantId) {
        EnjoySkuOrderResult enjoySkuOrderResult = new EnjoySkuOrderResult();
        Merchant merchant = merchantDao.findById(merchantId);
        DailiMerchantQuery dailiMerchantQuery = new DailiMerchantQuery();
        dailiMerchantQuery.setMobile(merchant.getMobile());
        DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(dailiMerchantQuery);
        if (dailiMerchant == null) {
            return enjoySkuOrderResult;
        }
        if (dailiMerchantId != null) {
            dailiMerchant = dailiMerchantDao.findById(dailiMerchantId);
        }
        if (!DailiMerchantRoleEnum.MERCHANT.getCode().equals(dailiMerchant.getRole())) {
            return enjoySkuOrderResult;
        }
        Page<SkuOrderResult> page = new Page<>(pagerInfo.getStart(), pagerInfo.getPageSize());
        Date dateTime = DateUtil.getDateTime(date, "yyyy-MM");
        Date startTime = DateUtil.getMinDateByMonth(dateTime);
        Date endTime = DateUtil.getMaxDateByMonth(dateTime);
        SkuOrderQuery param = new SkuOrderQuery();
        param.setNoStatus(SkuOrderStatusEnum.CANCEL.getCode());
        param.setMerchantId(merchantId);
        param.setStartTime(startTime);
        param.setEndTime(endTime);
        param.setOrderType(SkuOrderTypeEnum.ENJOY.getCode());
        Integer count = skuOrderDao.count(param);
        if (count > 0) {
            List<SkuOrder> skuOrderList = skuOrderDao.page(param, pagerInfo.getStart(), pagerInfo.getPageSize());
            List<SkuOrderResult> skuOrderResults = DTOUtils.convertList(skuOrderList, SkuOrderResult.class);
            for (SkuOrderResult skuOrderResult : skuOrderResults) {
                Double postagePrice = 0.0;
                Order order = orderDao.findById(skuOrderResult.getOrderId());
                skuOrderResult.setAddress(order.getAddress());
                skuOrderResult.setMerchantCityId(order.getMerchantCityId());
                SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
                skuOrderDetailQuery.setSkuOrderId(skuOrderResult.getId());
                List<SkuOrderDetail> list = skuOrderDetailDao.list(skuOrderDetailQuery);
                List<SkuOrderDetailResult> skuOrderDetailResults = DTOUtils.convertList(list, SkuOrderDetailResult.class);
                for (SkuOrderDetailResult skuOrderDetailResult : skuOrderDetailResults) {
                    Sku sku = skuDao.findByIdAndDelete(skuOrderDetailResult.getSkuId());
                    if (sku != null) {
                        skuOrderDetailResult.setSkuName(sku.getTitle());
                        SkuContent skuContent = skuContentDao.findBySkuId(skuOrderDetailResult.getSkuId());
                        if (skuContent != null) {
                            skuOrderDetailResult.setCover(skuContent.getCover());
                            skuOrderResult.setSkuOrderDetailResults(skuOrderDetailResults);
                        }
                        SkuCategory skuCategory = skuCategoryDao.findById(sku.getCategoryId());
                        if (skuCategory != null)
                            skuOrderDetailResult.setCategoryName(skuCategory.getName());
                    }
                    SkuOrderDeliveryDemandQuery skuOrderDeliveryDemandQuery = new SkuOrderDeliveryDemandQuery();
                    skuOrderDeliveryDemandQuery.setSkuOrderId(skuOrderDetailResult.getSkuOrderId());
                    SkuOrderDeliveryDemand skuOrderDeliveryDemand = skuOrderDeliveryDemandDao.findFirst(skuOrderDeliveryDemandQuery);
                    if (skuOrderDeliveryDemand != null) {
                        SkuOrderDeliveryDemandResult skuOrderDeliveryDemandResult = new SkuOrderDeliveryDemandResult();
                        BeanUtils.copyProperties(skuOrderDeliveryDemandResult, skuOrderDeliveryDemand);
                        skuOrderResult.setSkuOrderDeliveryDemandResult(skuOrderDeliveryDemandResult);
                        if (DeliveryWayEnum.FULLREDUCTION.getCode().equals(skuOrderDeliveryDemand.getLogistics())) {
                            postagePrice += skuOrderDeliveryDemand.getPostage();
                        }
                    }
                }
                skuOrderResult.setSkuPrice(skuOrderResult.getPayPrice());
                skuOrderResult.setPostagePrice(postagePrice);
                skuOrderResult.setPayPrice(postagePrice + skuOrderResult.getPayPrice());
            }
            page.setData(skuOrderResults);
        }
        Double enjoymonthPayPrice = skuOrderDao.getEnjoyPayPrice(merchantId, startTime, endTime);
        Double enjoyPayPrice = skuOrderDao.getEnjoyPayPrice(merchantId, null, null);
        enjoySkuOrderResult.setSkuOrderResultPage(page);
        enjoySkuOrderResult.setMonthAmount(enjoymonthPayPrice);
        if (dailiMerchant.getQuota() != null) {
            enjoySkuOrderResult.setAmount(dailiMerchant.getQuota());
            enjoySkuOrderResult.setSurplusQuota(dailiMerchant.getQuota() - enjoyPayPrice);
        }
        return enjoySkuOrderResult;
    }

    @Override
    public void confirmOrder(Integer id, Integer merchantId) throws BusinessException {
        SkuOrder skuOrder = skuOrderDao.findByIdAndMerchantId(id, merchantId);
        ValidateBusinessException.assertNonNull(skuOrder, ExceptionEnum.ERROR_1801);
        if (OrderTypeEnum.CAR.getCode().equals(skuOrder.getType())) {
            skuOrderDao.updateStatusByOrderId(skuOrder.getOrderId(), SkuOrderStatusEnum.SUCCESS.getCode());
        } else {
            SkuOrder param = new SkuOrder();
            param.setId(skuOrder.getId());
            param.setStatus(SkuOrderStatusEnum.SUCCESS.getCode());
            param.setFinishTime(new Date());
            skuOrderDao.updateById(param);
        }
    }

    @Override
    public void cancelOrder(Integer id, Integer merchantId, String applyRefundReason) throws BusinessException {
        SkuOrder skuOrder = skuOrderDao.findById(id);
        ValidateBusinessException.assertNonNull(skuOrder, ExceptionEnum.ERROR_1801);
        Order order = orderDao.findById(skuOrder.getOrderId());
        ValidateBusinessException.assertTrue((skuOrder.getMerchantId().equals(merchantId) || order.getPlaceMerchantId().equals(merchantId)), ExceptionEnum.ERROR_1801);
        ValidateBusinessException.assertFalse(SkuOrderStatusEnum.CANCEL.getCode().equals(skuOrder.getStatus()), ExceptionEnum.ERROR_1847);
        if (SkuOrderTypeEnum.BUY.getCode().equals(skuOrder.getOrderType()) && !SkuOrderStatusEnum.WAITING.getCode().equals(skuOrder.getStatus())) {
            throw BusinessException.build(ExceptionEnum.ERROR_1854);
        }
        if (SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrder.getOrderType()) && (SkuOrderStatusEnum.DELIVER.getCode().equals(skuOrder.getStatus()) || SkuOrderStatusEnum.SUCCESS.getCode().equals(skuOrder.getStatus()))) {
            throw BusinessException.build(ExceptionEnum.ERROR_1872);
        }
        Merchant merchant = merchantDao.findById(merchantId);
        SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
        skuOrderDetailQuery.setSkuOrderId(skuOrder.getId());
        SkuOrderDetail skuOrderDetail = skuOrderDetailDao.findFirst(skuOrderDetailQuery);
        //先享后付取消后退积分
        if (SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrder.getOrderType())
                && (SkuOrderStatusEnum.PAY.getCode().equals(skuOrder.getStatus()) || SkuOrderStatusEnum.WAITDELIVER.getCode().equals(skuOrder.getStatus()))) {
            SkuOrderDetail updateSkuOrderDetail = new SkuOrderDetail();
            updateSkuOrderDetail.setSkuOrderId(skuOrder.getId());
            updateSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.WAITINGCANCEL.getCode());
            updateSkuOrderDetail.setApplyRefundReason(applyRefundReason);
            updateSkuOrderDetail.setApplyRefundTime(new Date());
            skuOrderDetailDao.updateBySkuOrderId(updateSkuOrderDetail);
        } else if (SkuOrderTypeEnum.OFFLINE.getCode().equals(skuOrder.getOrderType())) {
            skuOrderDao.updateStatusByOrderId(skuOrder.getOrderId(), SkuOrderStatusEnum.CANCEL.getCode());
        } else {
            SkuOrder param = new SkuOrder();
            param.setId(skuOrder.getId());
            param.setStatus(SkuOrderStatusEnum.CANCEL.getCode());
            skuOrderDao.updateById(param);
        }

    }

    MerchantCity getMerchantCity(Integer merchantCityId) {
        MerchantCity merchantCity = merchantCityDao.findById(merchantCityId);
        if (merchantCity != null) {
            if (merchantCity.getProvinceId() != null) {
                GtRegion province = gtRegionDao.findById(merchantCity.getProvinceId());
                if (province != null)
                    merchantCity.setProvinceName(province.getName());
            }
            if (merchantCity.getCityId() != null) {
                GtRegion city = gtRegionDao.findById(merchantCity.getCityId());
                if (city != null)
                    merchantCity.setCityName(city.getName());
            }
            if (merchantCity.getAreaId() != null) {
                GtRegion area = gtRegionDao.findById(merchantCity.getAreaId());
                if (area != null)
                    merchantCity.setAreaName(area.getName());
            }
            return merchantCity;
        } else {
            return null;
        }
    }

    @Override
    public SkuOrderResult getSkuOrderResultDetail(Integer skuOrderId, Integer merchantId) throws BusinessException {
        SkuOrderResult skuOrderResult = new SkuOrderResult();
        SkuOrder skuOrder = skuOrderDao.findByIdAndMerchantId(skuOrderId, merchantId);
        ValidateBusinessException.assertNonNull(skuOrder, ExceptionEnum.ERROR_1801);
        BeanUtils.copyProperties(skuOrderResult, skuOrder);
        Order order = orderDao.findById(skuOrder.getOrderId());
        skuOrderResult.setCreateTime(order.getCreateTime());
        skuOrderResult.setMerchantCityId(order.getMerchantCityId());
        skuOrderResult.setAddress(order.getAddress());
        skuOrderResult.setReceiver(order.getReceiver());
        skuOrderResult.setReceiverMobile(order.getReceiverMobile());
        SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
        skuOrderDetailQuery.setSkuOrderId(skuOrderResult.getId());
        List<SkuOrderDetail> list = skuOrderDetailDao.list(skuOrderDetailQuery);
        List<SkuOrderDetailResult> skuOrderDetailResults = DTOUtils.convertList(list, SkuOrderDetailResult.class);
        Double postagePrice = 0.0;
        Double modifyPrice = 0.0;
        for (SkuOrderDetailResult skuOrderDetailResult : skuOrderDetailResults) {
            Sku sku = skuDao.findById(skuOrderDetailResult.getSkuId());
            if (sku != null) {
                skuOrderDetailResult.setSkuName(sku.getTitle());
                SkuContent skuContent = skuContentDao.findBySkuId(skuOrderDetailResult.getSkuId());
                if (skuContent != null) {
                    skuOrderDetailResult.setCover(skuContent.getCover());
                    if ("Y".equals(skuContent.getIsSpellOrder()) && SkuTypeEnum.PART.getCode().equals(skuOrder.getType())) {
                        SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
                        skuOrderQuery.setPartSn(skuOrder.getPartSn());
                        skuOrderQuery.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
                        Integer scount = skuOrderDao.count(skuOrderQuery);
                        skuOrderResult.setFewpeople(skuContent.getSpellOrderPeople() - scount);
                    }
                }
                SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuOrderDetailResult.getSkuSalesInformationId());
                if (skuSalesInformation != null) {
                    if (StringUtils.isNotBlank(skuSalesInformation.getCover())) {
                        skuOrderDetailResult.setCover(skuSalesInformation.getCover());
                    }
                }
                SkuCategory skuCategory = skuCategoryDao.findById(sku.getCategoryId());
                if (skuCategory != null)
                    skuOrderDetailResult.setCategoryName(skuCategory.getName());
            }
            if ("Y".equals(skuOrderDetailResult.getIsModifyPrice())) {
                modifyPrice += skuOrderDetailResult.getModifyPrice();
            } else {
                modifyPrice += skuOrderDetailResult.getPayPrice();
            }
        }
        if ("Y".equals(skuOrderResult.getIsModifyPrice())) {
            skuOrderResult.setModifyPrice(modifyPrice);
        }
        SkuOrderDeliveryDemandQuery param = new SkuOrderDeliveryDemandQuery();
        param.setMerchantId(merchantId);
        param.setSkuOrderId(skuOrder.getId());
        param.setNoPostageStatus(SkuOrderStatusEnum.CANCEL.getCode());
        SkuOrderDeliveryDemand skuOrderDeliveryDemand = skuOrderDeliveryDemandDao.findFirst(param);
        if (skuOrderDeliveryDemand != null) {
            if (DeliveryWayEnum.FULLREDUCTION.getCode().equals(skuOrderDeliveryDemand.getLogistics())) {
                postagePrice += skuOrderDeliveryDemand.getPostage();
            }
            SkuOrderDeliveryDemandResult skuOrderDeliveryDemandResult = new SkuOrderDeliveryDemandResult();
            BeanUtils.copyProperties(skuOrderDeliveryDemandResult, skuOrderDeliveryDemand);
            skuOrderResult.setSkuOrderDeliveryDemandResult(skuOrderDeliveryDemandResult);
        }
        skuOrderResult.setSkuPrice(skuOrderResult.getPayPrice());
        skuOrderResult.setPostagePrice(postagePrice);
        skuOrderResult.setPayPrice(postagePrice + skuOrderResult.getPayPrice());
        if (SkuOrderStatusEnum.WAITING.getCode().equals(skuOrderResult.getStatus())) {
            PlatformSystemDeploy platformSystemDeploy = getPlatformSystemDeploy(SkuTypeEnum.SKU.getCode(), SkuOrderStatusEnum.WAITING.getCode());
            if (platformSystemDeploy != null) {
                skuOrderResult.setExpireTime(getWebExpireTime(platformSystemDeploy.getUnit(), platformSystemDeploy.getDetails().intValue(), order.getCreateTime()));
            }
        } else if (SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrderResult.getOrderType())
                && "N".equals(skuOrderResult.getIsPay())
                && !SkuOrderStatusEnum.CANCEL.getCode().equals(skuOrderResult.getStatus())) {
            skuOrderResult.setStatus(SkuOrderStatusEnum.WAITING.getCode());
            skuOrderResult.setExpireTime(getEnjoyEndTime(order.getCreateTime()));
        }
        skuOrderResult.setSkuOrderDetailResults(skuOrderDetailResults);
        return skuOrderResult;
    }

    @Override
    public SkuOrderResult getSkuOrderResultDetailBySupplier(Integer skuOrderId, Integer supplierId, String roleType) throws BusinessException {
        SkuOrderResult skuOrderResult = new SkuOrderResult();
        SkuOrder skuOrder = skuOrderDao.findById(skuOrderId);
        if (RoleTypeEnum.SUPPLIER.getCode().equals(roleType)) {
            ValidateBusinessException.assertTrue(supplierId.equals(skuOrder.getSupplierId()), ExceptionEnum.ERROR_1815);
        }
        ValidateBusinessException.assertNonNull(skuOrder, ExceptionEnum.ERROR_1801);
        BeanUtils.copyProperties(skuOrderResult, skuOrder);
        Order order = orderDao.findById(skuOrder.getOrderId());
        skuOrderResult.setCreateTime(order.getCreateTime());
        skuOrderResult.setAddress(order.getAddress());
        skuOrderResult.setReceiver(order.getReceiver());
        skuOrderResult.setReceiverMobile(order.getReceiverMobile());
        SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
        skuOrderDetailQuery.setSkuOrderId(skuOrderResult.getId());
        List<SkuOrderDetail> list = skuOrderDetailDao.list(skuOrderDetailQuery);
        List<SkuOrderDetailResult> skuOrderDetailResults = DTOUtils.convertList(list, SkuOrderDetailResult.class);
        Double modifyPrice = 0.0;
        for (SkuOrderDetailResult skuOrderDetailResult : skuOrderDetailResults) {
            SkuOrderDeliveryDemandQuery param = new SkuOrderDeliveryDemandQuery();
            param.setSkuOrderId(skuOrderDetailResult.getSkuOrderId());
            param.setSkuOrderDetailId(skuOrderDetailResult.getId());
            //退款状态
            skuOrderDetailResult.setStatus(skuOrder.getStatus());
            Sku sku = skuDao.findById(skuOrderDetailResult.getSkuId());
            if (sku != null) {
                skuOrderDetailResult.setSkuName(sku.getTitle());
                SkuContent skuContent = skuContentDao.findBySkuId(skuOrderDetailResult.getSkuId());
                if (skuContent != null)
                    skuOrderDetailResult.setCover(skuContent.getCover());
                SkuCategory skuCategory = skuCategoryDao.findById(sku.getCategoryId());
                if (skuCategory != null)
                    skuOrderDetailResult.setCategoryName(skuCategory.getName());
                SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuOrderDetailResult.getSkuSalesInformationId());
                if (skuSalesInformation != null) {
                    skuOrderDetailResult.setProductName(skuSalesInformation.getProductName());
                    skuOrderDetailResult.setSpecifications(skuSalesInformation.getSpecifications());
                    skuOrderDetailResult.setUnit(skuSalesInformation.getUnit());
                }
            }
            if ("Y".equals(skuOrderDetailResult.getIsModifyPrice())) {
                modifyPrice += skuOrderDetailResult.getModifyPrice();
            } else {
                modifyPrice += skuOrderDetailResult.getPayPrice();
            }
        }
        if ("Y".equals(skuOrderResult.getIsModifyPrice())) {
            skuOrderResult.setModifyPrice(modifyPrice);
        }
        List<SkuOrderDeliveryDemandResult> skuOrderDeliveryDemandResult = skuOrderDeliveryDemandDao.getSkuOrderDeliveryDemandResult(skuOrder.getId());
        if (CollectionUtils.isNotEmpty(skuOrderDeliveryDemandResult)) {
            for (SkuOrderDeliveryDemandResult orderDeliveryDemandResult : skuOrderDeliveryDemandResult) {
                if (DeliveryWayEnum.FULLREDUCTION.getCode().equals(orderDeliveryDemandResult.getLogistics())) {
                    if (orderDeliveryDemandResult.getPostage() == 0) {
                        orderDeliveryDemandResult.setIsFreeShipping("Y");
                    }
                }
            }
        }
        Merchant merchant = merchantDao.findById(order.getMerchantId());
        if (merchant != null) {
            skuOrderResult.setMerchantMobile(merchant.getMobile());
            DailiMerchantQuery dailiMerchantQuery = new DailiMerchantQuery();
            dailiMerchantQuery.setMobile(merchant.getMobile());
            DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(dailiMerchantQuery);
            if (dailiMerchant != null) {
                DailiMerchant dailiMerchant1 = dailiMerchantDao.findById(dailiMerchant.getPid());
                if (dailiMerchant1 != null) {
                    MerchantQuery merchantQuery = new MerchantQuery();
                    merchantQuery.setMobile(dailiMerchant1.getMobile());
                    Merchant merchant1 = merchantDao.findFirst(merchantQuery);
                    if (merchant1 != null) {
                        skuOrderResult.setPlaceMerchantMobile(merchant1.getMobile());
                        skuOrderResult.setPlaceMerchantName(merchant1.getName());
                    }
                }
            }
        }
        skuOrderResult.setSkuOrderDetailResults(skuOrderDetailResults);
        skuOrderResult.setSkuOrderDeliveryDemandResults(skuOrderDeliveryDemandResult);
        if (skuOrder.getOrderType().equals(SkuSalesInformationTypeEnum.PERIODIZATION.getCode())) {
            List<PeriodizationOrderSkuResult> periodizationOrderSkuResults = new ArrayList<>();
            List<SkuOrder> skuOrders = skuOrderDao.getListByOrderId(SkuOrderStatusEnum.SUCCESS.getCode(), skuOrder.getOrderId());
            for (int i = 0; i < skuOrders.size(); i++) {
                SkuOrder skuOrdera = skuOrders.get(i);
                PeriodizationOrderSkuResult periodizationOrderSkuResult = new PeriodizationOrderSkuResult();
                SkuOrderDetailQuery skuOrderDetailQuery1 = new SkuOrderDetailQuery();
                skuOrderDetailQuery1.setSkuOrderId(skuOrdera.getId());
                List<SkuOrderDetail> skuOrderDetailList = skuOrderDetailDao.list(skuOrderDetailQuery1);
                List<SkuOrderDetailResult> skuOrderDetailResults1 = DTOUtils.convertList(skuOrderDetailList, SkuOrderDetailResult.class);
                for (SkuOrderDetailResult skuOrderDetailResult : skuOrderDetailResults1) {
                    Sku sku = skuDao.findById(skuOrderDetailResult.getSkuId());
                    SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuOrderDetailResult.getSkuSalesInformationId());
                    if (sku != null) {
                        SkuContent skuContent = skuContentDao.findBySkuId(sku.getId());
                        skuOrderDetailResult.setCover(skuContent.getCover());
                        SkuOrderDetailPeriodizationQuery skuOrderDetailPeriodizationQuery = new SkuOrderDetailPeriodizationQuery();
                        skuOrderDetailPeriodizationQuery.setSkuOrderDetailId(skuOrderDetailResult.getId());
                        SkuOrderDetailPeriodization skuOrderDetailPeriodization = skuOrderDetailPeriodizationDao.findFirst(skuOrderDetailPeriodizationQuery);
                        if (skuOrderDetailPeriodization != null) {
                            skuOrderDetailResult.setExtractSpecifications(skuOrderDetailPeriodization.getExtractSpecifications());
                        }
                        skuOrderDetailResult.setSkuName(sku.getTitle());
                    }
                    if (skuSalesInformation != null) {
                        skuOrderDetailResult.setUnit(skuSalesInformation.getUnit());
                    }
                }
                periodizationOrderSkuResult.setCreateTime(skuOrdera.getCreateTime());
                periodizationOrderSkuResult.setPeriodsNumber(skuOrdera.getPeriodsNumber());
                periodizationOrderSkuResult.setId(skuOrdera.getId());
                periodizationOrderSkuResult.setTotalPayPrice(skuOrdera.getPayPrice());
                periodizationOrderSkuResult.setStatus(skuOrdera.getStatus());
                periodizationOrderSkuResult.setSkuOrderDetailResults(skuOrderDetailResults1);
                periodizationOrderSkuResults.add(periodizationOrderSkuResult);
            }
            skuOrderResult.setPeriodizationOrderSkuResults(periodizationOrderSkuResults);
        }

        return skuOrderResult;
    }

    PlatformSystemDeploy getPlatformSystemDeploy(String type, String status) {
        PlatformSystemDeployQuery platformSystemDeployQuery = new PlatformSystemDeployQuery();
        platformSystemDeployQuery.setType(type);
        platformSystemDeployQuery.setStatus(status);
        PlatformSystemDeploy platformSystemDeploy = platformSystemDeployDao.findFirst(platformSystemDeployQuery);
        return platformSystemDeploy;
    }

    @Override
    public void cancelWaitingOrder() {
        PlatformSystemDeploy platformSystemDeploy = getPlatformSystemDeploy(SkuTypeEnum.SKU.getCode(), SkuOrderStatusEnum.WAITING.getCode());
        if (platformSystemDeploy == null) {
            return;
        }
        SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
        skuOrderQuery.setStatus(InquireOrderStatusEnum.WAITING.getCode());
        skuOrderQuery.setWaitingExpireTime(getExpireTime(platformSystemDeploy.getUnit(), platformSystemDeploy.getDetails().intValue()));
        List<SkuOrder> list = skuOrderDao.list(skuOrderQuery);
        for (SkuOrder skuOrder : list) {
            SkuOrder update = new SkuOrder();
            update.setId(skuOrder.getId());
            update.setStatus(InquireOrderStatusEnum.CANCEL.getCode());
            skuOrderDao.updateById(update);
        }
    }

    @Override
    public void transactionFinash() {
        PlatformSystemDeploy platformSystemDeploy = getPlatformSystemDeploy(SkuTypeEnum.SKU.getCode(), SkuOrderStatusEnum.DELIVER.getCode());
        if (platformSystemDeploy == null) {
            return;
        }
        SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
        skuOrderQuery.setNoStatus(SkuOrderStatusEnum.SUCCESS.getCode());
        skuOrderQuery.setIsPay("Y");
        skuOrderQuery.setEndTime(getExpireTime(platformSystemDeploy.getUnit(), platformSystemDeploy.getDetails().intValue()));
        List<SkuOrder> list = skuOrderDao.list(skuOrderQuery);
        for (SkuOrder skuOrder : list) {
            SkuOrder update = new SkuOrder();
            update.setId(skuOrder.getId());
            update.setStatus(InquireOrderStatusEnum.SUCCESS.getCode());
            skuOrderDao.updateById(update);
        }

    }

    @Override
    public void cancelWatiPartOrder() {
        SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
        skuOrderQuery.setIsSponsor("Y");
        skuOrderQuery.setPartStatus(SkuOrderStatusEnum.WAITING.getCode());
        skuOrderQuery.setStartPartFinshTime(new Date());
        List<SkuOrder> list = skuOrderDao.list(skuOrderQuery);
        logger.info("cancelWatiPartOrder====" + JSONObject.toJSONString(list));
        if (list != null && list.size() > 0) {
            for (SkuOrder skuOrder : list) {
                SkuOrderQuery partSn = new SkuOrderQuery();
                partSn.setPartSn(skuOrder.getPartSn());
                partSn.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
                List<SkuOrder> skuOrderList = skuOrderDao.list(partSn);
                logger.info("cancelWatiPartOrderskuOrderList====" + JSONObject.toJSONString(skuOrderList));
                if (skuOrderList != null && skuOrderList.size() > 0) {
                    for (SkuOrder order : skuOrderList) {
                        SkuOrderDetailQuery param = new SkuOrderDetailQuery();
                        param.setSkuOrderId(order.getId());
                        List<SkuOrderDetail> list1 = skuOrderDetailDao.list(param);
                        logger.info("cancelWatiPartOrderskulist1====" + JSONObject.toJSONString(list1));
                        if (list1 != null && list1.size() > 0) {
                            for (SkuOrderDetail skuOrderDetail : list1) {
                                if (StringUtils.isEmpty(skuOrderDetail.getApplyRefundStatus())) {
                                    SkuOrderDetail update = new SkuOrderDetail();
                                    update.setApplyRefundStatus(SkuOrderStatusEnum.APPLYING.getCode());
                                    update.setApplyRefundTime(new Date());
                                    update.setApplyRefundReason("拼团失败,退款");
                                    update.setId(skuOrderDetail.getId());
                                    skuOrderDetailDao.updateById(update);
                                }
                            }
                        }
                    }
                }
            }
        }


    }

    @Override
    public List<Map<String, String>> remindEnjoyOrder(Date date) {
        List<Map<String, String>> listMap = new ArrayList<>();
        int yearInteger = DateUtil.getYearInteger(date);
        int monthInteger = DateUtil.getMonthInteger(date);
        Date startTime = DateUtil.setMinDate(DateUtil.getFirstDayOfCurMonth(yearInteger, monthInteger - 1));
        Date endTime = DateUtil.setMaxDate(DateUtil.getLastDayOfCurMonth(yearInteger, monthInteger - 1));
        DailiMerchantQuery dailiMerchantQuery = new DailiMerchantQuery();
        dailiMerchantQuery.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
        dailiMerchantQuery.setIsEnable("Y");
        dailiMerchantQuery.setRole(DailiMerchantRoleEnum.MERCHANT.getCode());
        dailiMerchantQuery.setNoQuota(0.0);
        List<DailiMerchant> list = dailiMerchantDao.list(dailiMerchantQuery);
        for (DailiMerchant dailiMerchant : list) {
            MerchantQuery param = new MerchantQuery();
            param.setMobile(dailiMerchant.getMobile());
            Merchant merchant = merchantDao.findFirst(param);
            Double enjoyDay = skuOrderDao.getEnjoyPayPrice(merchant.getId(), startTime, endTime);
            if (enjoyDay > 0 && StringUtils.isNotBlank(merchant.getGzhOpenId())) {
                Map<String, String> map = new HashMap<>();
                map.put("merchantId", merchant.getId() + "");
                map.put("openId", merchant.getGzhOpenId());
                map.put("enjoyDay", enjoyDay + "");
                map.put("date", DateUtil.date(date, "yyyy-MM"));
                listMap.add(map);
            }
        }
        logger.info("listMap===" + JSONObject.toJSONString(listMap));
        return listMap;
    }

    @Override
    public List<Map<String, String>> remindPeriodizationOrder(Date date) {
        List<Map<String, String>> listMap = new ArrayList<>();
        int dayInteger = DateUtil.getDayInteger(date);
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setType(SkuSalesInformationTypeEnum.PERIODIZATION.getCode());
        orderQuery.setStatus(SkuOrderStatusEnum.WAITING.getCode());
        List<Order> list = orderDao.list(orderQuery);
        for (Order order : list) {
            if (order.getRemindDate() == dayInteger || order.getRemindDate() + 1 == dayInteger || order.getRemindDate() + 2 == dayInteger) {
                SkuOrderQuery skuOrderQuery = new SkuOrderQuery();
                skuOrderQuery.setOrderId(order.getId());
                skuOrderQuery.setStartTime(DateUtil.getMinDateByMonth(date));
                skuOrderQuery.setEndTime(DateUtil.getMaxDateByMonth(date));
                skuOrderQuery.setNoStatus(SkuOrderStatusEnum.CANCEL.getCode());
                List<SkuOrder> list1 = skuOrderDao.list(skuOrderQuery);
                if (list1.size() <= 0) {
                    Merchant merchant = merchantDao.findById(order.getMerchantId());
                    Map<String, String> map = new HashMap<>();
                    map.put("merchantId", merchant.getId() + "");
                    map.put("openId", merchant.getGzhOpenId());
                    map.put("date", DateUtil.date(date, "yyyy-MM-dd"));
                    listMap.add(map);
                }
            }
        }
        return listMap;
    }

    @Override
    public Boolean isEnjoy(SkuOrderAddByDirectReq req) throws BusinessException {
        Merchant merchant = merchantDao.findById(req.getMerchantId());
        DailiMerchantQuery dailiMerchantQuery = new DailiMerchantQuery();
        dailiMerchantQuery.setMobile(merchant.getMobile());
        dailiMerchantQuery.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
        dailiMerchantQuery.setIsEnable("Y");
        dailiMerchantQuery.setRole(DailiMerchantRoleEnum.MERCHANT.getCode());
        DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(dailiMerchantQuery);
        if (dailiMerchant == null) {
            throw BusinessException.build(ExceptionEnum.ERROR_1869);
        }
        if (dailiMerchant.getQuota() == null || dailiMerchant.getQuota() == 0) {
            throw BusinessException.build(ExceptionEnum.ERROR_1869);
        }
        Integer skuId = req.getSkuId();
        Sku sku = skuDao.findById(skuId);
        ValidateBusinessException.assertNonNull(sku, ExceptionEnum.ERROR_1701);
        ValidateBusinessException.assertFalse("N".equals(sku.getIsEnable()), ExceptionEnum.ERROR_1702);
        SkuContent skuContent = skuContentDao.findBySkuId(skuId);
        ValidateBusinessException.assertNonNull(skuContent, ExceptionEnum.ERROR_1701);
        ValidateBusinessException.assertFalse("Y".equals(req.getIsSpellOrder()) && !"Y".equals(skuContent.getIsSpellOrder()), ExceptionEnum.ERROR_1856);
        SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(req.getSkuSalesInformationId());
        ValidateBusinessException.assertNonNull(skuSalesInformation, ExceptionEnum.ERROR_1703);
        ValidateBusinessException.assertFalse(skuSalesInformation.getStock() < req.getCount(), sku.getTitle() + (ExceptionEnum.ERROR_1816.getMessage()));
        //判断是否参与和拼团人数够
        if (StringUtils.isNotEmpty(req.getPartSn())) {
            SkuOrderQuery param = new SkuOrderQuery();
            param.setPartSn(req.getPartSn());
            param.setMerchantId(req.getMerchantId());
            param.setNoStatus(SkuOrderStatusEnum.CANCEL.getCode());
            SkuOrder first = skuOrderDao.findFirst(param);
            ValidateBusinessException.assertNull(first, ExceptionEnum.ERROR_1860);
            param = new SkuOrderQuery();
            param.setPartSn(req.getPartSn());
            param.setIsApply("N");
            param.setNoStatus(SkuOrderStatusEnum.WAITING.getCode());
            List<SkuOrder> list = skuOrderDao.list(param);
            if (list == null || list.size() <= 0) {
                throw new BusinessException(ExceptionEnum.ERROR_1851.getCode(), ExceptionEnum.ERROR_1851.getMessage());
            }
            if (list.size() >= skuContent.getSpellOrderPeople()) {
                throw new BusinessException(ExceptionEnum.ERROR_1852.getCode(), ExceptionEnum.ERROR_1852.getMessage());
            }
            param = new SkuOrderQuery();
            param.setPartSn(req.getPartSn());
            param.setIsApply("Y");
            SkuOrder skuOrder = skuOrderDao.findFirst(param);
            if (skuOrder.getPartFinshTime().before(new Date())) {
                throw new BusinessException(ExceptionEnum.ERROR_1859.getCode(), ExceptionEnum.ERROR_1859.getMessage());
            }
        }
        MerchantCity merchantCity = getMerchantCity(req.getMerchantCityId());
        //支付价格
        Double totalPayPrice = 0.0;
        Integer count = req.getCount();
        //总价
        double price = skuSalesInformation.getPrice() * count;
        if ("Y".equals(req.getIsSpellOrder())) {
            price = skuSalesInformation.getSpellOrderPrice() * count;
        }
        Integer cityId = req.getCityId();
        RegionalSkuSalesInformation regionalSkuSalesInformation = new RegionalSkuSalesInformation();
        if (cityId != null) {
            RegionalSkuSalesInformationQuery regionalSkuSalesInformationQuery = new RegionalSkuSalesInformationQuery();
            regionalSkuSalesInformationQuery.setGtRegionId(cityId);
            regionalSkuSalesInformationQuery.setSkuSalesInformationId(req.getSkuSalesInformationId());
            regionalSkuSalesInformation = regionalSkuSalesInformationDao.findFirst(regionalSkuSalesInformationQuery);
            if (regionalSkuSalesInformation != null) {
                price = new BigDecimal(regionalSkuSalesInformation.getRegionalPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            }
        }
        IntegerPrice ip = getIntegral(req.getIsUseIntegral(), price, merchant, skuContent, skuSalesInformation, regionalSkuSalesInformation);
        Double integralPrice = ip.getIntegralPrice();
        Double payPrice = new BigDecimal(price).subtract(new BigDecimal(integralPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
        payPrice = payPrice > 0 ? payPrice : 0;
        totalPayPrice += payPrice;
        //拼团商品操作
        if ("Y".equals(req.getIsSpellOrder()) && "Y".equals(skuContent.getIsSpellOrder())) {
            if (!merchantCity.getProvinceId().equals(skuContent.getSpellOrderProvinceId()) || !merchantCity.getCityId().equals(skuContent.getSpellOrderCityId())) {
                throw new BusinessException(ExceptionEnum.ERROR_1857.getCode(), ExceptionEnum.ERROR_1857.getMessage());
            }
            PlatformSystemDeployQuery secondPlatformSystemDeployQuery = new PlatformSystemDeployQuery();
            secondPlatformSystemDeployQuery.setType(SkuTypeEnum.PART.getCode());
            secondPlatformSystemDeployQuery.setStatus("finishTime");
            PlatformSystemDeploy secondPlatformSystemDeploy = platformSystemDeployDao.findFirst(secondPlatformSystemDeployQuery);
            ValidateBusinessException.assertNonNull(secondPlatformSystemDeploy, ExceptionEnum.ERROR_1705);
        }
        Double finalPayPrice = payPrice;
        Double enjoyPayPrice = skuOrderDao.getEnjoyPayPrice(req.getMerchantId(), null, null);
        if (enjoyPayPrice + finalPayPrice > dailiMerchant.getQuota()) {
            throw BusinessException.build(ExceptionEnum.ERROR_1870);
        }
        DailiMerchant partnerMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
        if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(partnerMerchant.getRole())) {
            partnerMerchant = dailiMerchantDao.findById(partnerMerchant.getPid());
        }
        DailiMerchantQuery partnerMerchantQuery = new DailiMerchantQuery();
        partnerMerchantQuery.setPidPath(partnerMerchant.getPidPath());
        partnerMerchantQuery.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
        partnerMerchantQuery.setIsEnable("Y");
        partnerMerchantQuery.setRole(DailiMerchantRoleEnum.MERCHANT.getCode());
        partnerMerchantQuery.setNoQuota(0.0);
        List<DailiMerchant> dailiMerchants = dailiMerchantDao.list(partnerMerchantQuery);
        List<String> mobileList = dailiMerchants.stream().map(DailiMerchant::getMobile).collect(Collectors.toList());
        List<Integer> merchantList = merchantDao.findByMobiles(mobileList).stream().map(Merchant::getId).collect(Collectors.toList());
        Double enjoyPayPriceByMerchantIds = skuOrderDao.getEnjoyPayPriceByMerchantIds(merchantList, null, null);
        if (enjoyPayPriceByMerchantIds + finalPayPrice > dailiMerchant.getQuota()) {
            throw BusinessException.build(ExceptionEnum.ERROR_1871);
        }
        return true;
    }

    @Override
    public Boolean isEnjoyByCar(SkuOrderAddReq req) throws BusinessException {
        if (CollectionUtils.isEmpty(req.getSkuShopcarId())) {
            return true;
        }
        Merchant merchant = merchantDao.findById(req.getMerchantId());
        DailiMerchantQuery dailiMerchantQuery = new DailiMerchantQuery();
        dailiMerchantQuery.setMobile(merchant.getMobile());
        dailiMerchantQuery.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
        dailiMerchantQuery.setIsEnable("Y");
        dailiMerchantQuery.setRole(DailiMerchantRoleEnum.MERCHANT.getCode());
        DailiMerchant dailiMerchant = dailiMerchantDao.findFirst(dailiMerchantQuery);
        if (dailiMerchant == null) {
            throw BusinessException.build(ExceptionEnum.ERROR_1869);
        }
        if (dailiMerchant.getQuota() == null || dailiMerchant.getQuota() == 0) {
            throw BusinessException.build(ExceptionEnum.ERROR_1869);
        }
        Double enjoyPayPrice = skuOrderDao.getEnjoyPayPrice(req.getMerchantId(), null, null);
        DailiMerchant partnerMerchant = dailiMerchantDao.findById(dailiMerchant.getPid());
        if (DailiMerchantRoleEnum.DISTRIBUTOR.getCode().equals(partnerMerchant.getRole())) {
            partnerMerchant = dailiMerchantDao.findById(partnerMerchant.getPid());
        }
        DailiMerchantQuery partnerMerchantQuery = new DailiMerchantQuery();
        partnerMerchantQuery.setPidPath(partnerMerchant.getPidPath());
        partnerMerchantQuery.setStatus(DailiMerchantStatusEnum.SUCCESS.getCode());
        partnerMerchantQuery.setIsEnable("Y");
        partnerMerchantQuery.setRole(DailiMerchantRoleEnum.MERCHANT.getCode());
        partnerMerchantQuery.setNoQuota(0.0);
        List<DailiMerchant> dailiMerchants = dailiMerchantDao.list(partnerMerchantQuery);
        List<String> mobileList = dailiMerchants.stream().map(DailiMerchant::getMobile).collect(Collectors.toList());
        List<Integer> merchantList = merchantDao.findByMobiles(mobileList).stream().map(Merchant::getId).collect(Collectors.toList());
        Double enjoyPayPriceByMerchantIds = skuOrderDao.getEnjoyPayPriceByMerchantIds(merchantList, null, null);
        OrderResult orderResult = new OrderResult();
        List<String> skuNames = new ArrayList<>();
        //总价
        Double totalPrice = 0.0;
        //支付价格
        Double totalPayPrice = 0.0;
        //积分价格
        Double integerPrice = 0.0;
        //积分
        Integer integralPrice = 0;
        //积分
        Double unitPrice = 0.0;
        //商户积分
        Integer merchantIntegral = merchant.getIntegral();
        //
        Double fullReductionPrice = 0.0;
        List<SkuOrderDetail> skuOrderDetails = new ArrayList<>();
        List<SkuShopcar> skuShopcars = skuShopcarDao.findByIds(req.getSkuShopcarId());
        for (SkuShopcar skuShopcar : skuShopcars) {
            SkuOrderDetail skuOrderDetail = new SkuOrderDetail();
            ValidateBusinessException.assertTrue(req.getMerchantId().equals(skuShopcar.getMerchantId()), ExceptionEnum.ERROR_1853);
            Integer count = skuShopcar.getCount();
            Sku sku = skuDao.findById(skuShopcar.getSkuId());
            ValidateBusinessException.assertNonNull(sku, ExceptionEnum.ERROR_1701);
            ValidateBusinessException.assertFalse("N".equals(sku.getIsEnable()), ExceptionEnum.ERROR_1702);
            skuNames.add(sku.getTitle());
            SkuContent skuContent = skuContentDao.findBySkuId(skuShopcar.getSkuId());
            ValidateBusinessException.assertNonNull(skuContent, ExceptionEnum.ERROR_1701);
            SkuSalesInformation skuSalesInformation = skuSalesInformationDao.findById(skuShopcar.getSkuSalesInformationId());
            ValidateBusinessException.assertNonNull(skuSalesInformation, ExceptionEnum.ERROR_1703);
            ValidateBusinessException.assertFalse(skuSalesInformation.getStock() < skuShopcar.getCount(), ExceptionEnum.ERROR_1816.getCode(), sku.getTitle() + (ExceptionEnum.ERROR_1816.getMessage()));
            EnjoyBeforePaySkuQuery enjoyBeforePaySkuQuery = new EnjoyBeforePaySkuQuery();
            enjoyBeforePaySkuQuery.setSkuId(sku.getId());
            EnjoyBeforePaySku enjoyBeforePaySku = enjoyBeforePaySkuDao.findFirst(enjoyBeforePaySkuQuery);
            if (enjoyBeforePaySku == null) {
                continue;
            }
            Double price = new BigDecimal(skuSalesInformation.getPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            unitPrice = skuSalesInformation.getPrice();
            RegionalSkuSalesInformation regionalSkuSalesInformation = getRegionalSkuSalesInformation(null, req.getCityId(), skuShopcar.getSkuSalesInformationId(), sku.getTitle());
            if (regionalSkuSalesInformation != null) {
                price = new BigDecimal(regionalSkuSalesInformation.getRegionalPrice() + "").multiply(new BigDecimal(count)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
                unitPrice = regionalSkuSalesInformation.getRegionalPrice();
                skuOrderDetail.setIsRegion("Y");
            }
            totalPrice += price;
            IntegerPrice ip = getIntegral(req.getIsUseIntegral(), price, merchant, skuContent, skuSalesInformation, regionalSkuSalesInformation);
            integralPrice = ip.getIntegral();
            integerPrice = ip.getIntegralPrice();
            //商户扣减积分
            merchantIntegral -= integralPrice;
            double payPrice = 0.0;
            if (price >= integerPrice) {
                payPrice = new BigDecimal(price).subtract(new BigDecimal(integerPrice)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            }
            totalPayPrice += payPrice;
            ValidateBusinessException.assertFalse("Y".equals(skuContent.getIsSpellOrder()), ExceptionEnum.ERROR_1707);
            if (skuContent.getLogistics().equals(DeliveryWayEnum.FULLREDUCTION.getCode())) {
                fullReductionPrice += payPrice;
            }
            skuOrderDetail.setSkuId(skuShopcar.getSkuId());
            skuOrderDetail.setSkuSalesInformationId(skuShopcar.getSkuSalesInformationId());
            skuOrderDetail.setSupplierId(sku.getSupplierId());
            skuOrderDetail.setPrice(unitPrice);
            skuOrderDetail.setCount(skuShopcar.getCount());
            skuOrderDetail.setDeliveryWay(skuContent.getLogistics());
            skuOrderDetail.setTotalPrice(price);
            skuOrderDetail.setPayPrice(payPrice);
            skuOrderDetail.setTotalInteger(integralPrice);
            skuOrderDetail.setIntegral(integralPrice);
            skuOrderDetail.setMerchantId(req.getMerchantId());
            skuOrderDetails.add(skuOrderDetail);
        }
        Boolean isHavingPostage = false;
        Double freight = 0.0;
        if (fullReductionPrice > 0.0) {
            UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
            urbanFullReductionQuery.setCityId(req.getCityId());
            UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            if (urbanFullReductionDaoFirst == null) {
                urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
            }
            if (fullReductionPrice < urbanFullReductionDaoFirst.getMoney()) {
                isHavingPostage = true;
                freight = urbanFullReductionDaoFirst.getFreight();
            }
        }
        if (enjoyPayPrice + totalPayPrice + freight > dailiMerchant.getQuota()) {
            throw BusinessException.build(ExceptionEnum.ERROR_1870);
        }
        if (enjoyPayPriceByMerchantIds + totalPayPrice + freight > partnerMerchant.getQuota()) {
            throw BusinessException.build(ExceptionEnum.ERROR_1871);
        }
        return true;
    }

    public IntegerPrice getIntegral(String isUseIntegral, Double price, Merchant merchant, SkuContent skuContent, SkuSalesInformation skuSalesInformation, RegionalSkuSalesInformation regionalSkuSalesInformation) throws BusinessException {
        //积分价格
        Double integralPrice = 0.0;
        //积分
        Integer integral = 0;
        //计算积分抵扣金额
        if ("Y".equals(skuContent.getIsIntegral()) && "Y".equals(isUseIntegral)) {
            PlatformSystemDeploy platformSystemDeploy = jfPlatformSystemDeploy();
            Double integralDeduction = skuContent.getIntegralDeduction();
            if (skuSalesInformation.getIntegralDeduction() != null) {
                integralDeduction = skuSalesInformation.getIntegralDeduction();
            }
            if (regionalSkuSalesInformation != null && regionalSkuSalesInformation.getIntegralDeduction() != null) {
                integralDeduction = regionalSkuSalesInformation.getIntegralDeduction();
            }
            integral = new BigDecimal(price + "").multiply(new BigDecimal(integralDeduction)).divide(new BigDecimal(platformSystemDeploy.getDetails()), BigDecimal.ROUND_HALF_EVEN).multiply(new BigDecimal(platformSystemDeploy.getUnit())).setScale(0, BigDecimal.ROUND_UP).intValue();
            if (merchant.getIntegral() > integral) {
                integralPrice = new BigDecimal(price + "").multiply(new BigDecimal(integralDeduction)).setScale(2, RoundingMode.HALF_EVEN).doubleValue();
            } else if (merchant.getIntegral() > 0) {
                integralPrice = new BigDecimal(merchant.getIntegral()).divide(new BigDecimal(platformSystemDeploy.getUnit()), 2, BigDecimal.ROUND_HALF_EVEN).multiply(new BigDecimal(platformSystemDeploy.getDetails())).setScale(2).doubleValue();
                integral = merchant.getIntegral();
            } else {
                integral = 0;
            }
        }
        IntegerPrice integerPrice = new IntegerPrice();
        integerPrice.setIntegral(integral);
        integerPrice.setIntegralPrice(integralPrice);
        return integerPrice;

    }

    @Override
    public void applyRefund(Integer merchantId, Integer skuOrderDetailId, String applyRefundReason) throws BusinessException {
        Merchant merchant = merchantDao.findById(merchantId);
        SkuOrderDetail skuOrderDetail = skuOrderDetailDao.findByIdAndMerchantId(skuOrderDetailId, merchantId);
        ValidateBusinessException.assertNonNull(skuOrderDetail, ExceptionEnum.ERROR_1801);
        SkuOrder skuOrder = skuOrderDao.findById(skuOrderDetail.getSkuOrderId());
        ValidateBusinessException.assertFalse(SkuOrderStatusEnum.CANCEL.getCode().equals(skuOrder.getStatus()), ExceptionEnum.ERROR_1847);
        ValidateBusinessException.assertFalse(SkuOrderStatusEnum.APPLYING.getCode().equals(skuOrderDetail.getApplyRefundStatus()), ExceptionEnum.ERROR_1803);
        ValidateBusinessException.assertFalse(SkuOrderStatusEnum.SUCCESS.getCode().equals(skuOrderDetail.getApplyRefundStatus()), ExceptionEnum.ERROR_1804);
        ValidateBusinessException.assertFalse("N".equals(skuOrder.getIsPay()), ExceptionEnum.ERROR_1874);
        if (SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrder.getOrderType())
                && (SkuOrderStatusEnum.PAY.getCode().equals(skuOrder.getStatus()) || SkuOrderStatusEnum.WAITDELIVER.getCode().equals(skuOrder.getStatus()))) {
            SkuOrderDetail updateSkuOrderDetail = new SkuOrderDetail();
            updateSkuOrderDetail.setId(skuOrderDetail.getId());
            updateSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.PASS.getCode());
            updateSkuOrderDetail.setApplyRefundTime(new Date());
            updateSkuOrderDetail.setApplyRefundReason(applyRefundReason);
            skuOrderDetailDao.updateById(updateSkuOrderDetail);
            logger.info("updateSkuOrderDetail===" + JSONObject.toJSONString(updateSkuOrderDetail));
            SkuOrder updateSkuOrder = new SkuOrder();
            updateSkuOrder.setId(skuOrder.getId());
            updateSkuOrder.setStatus(SkuOrderStatusEnum.CANCEL.getCode());
            skuOrderDao.updateById(updateSkuOrder);
            logger.info("getIntegral===" + skuOrderDetail.getIntegral());
            if (skuOrderDetail.getIntegral() != null && skuOrderDetail.getIntegral() > 0) {
                merchantDao.addIntegral(merchantId, skuOrderDetail.getIntegral());
                MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
                merchantIntegralLog.setMerchantId(merchantId);
                merchantIntegralLog.setOperation(IntegralOperationEnum.REFUND.getCode());
                merchantIntegralLog.setBeforeIntegral(merchant.getIntegral());
                Merchant afterMerchant = merchantDao.findById(skuOrderDetail.getMerchantId());
                merchantIntegralLog.setAfterIntegral(afterMerchant.getIntegral());
                merchantIntegralLog.setRemarks("退款");
                merchantIntegralLog.setCreateTime(new Date());
                merchantIntegralLogDao.insert(merchantIntegralLog);
            }
        } else {
            SkuOrderDetail updateSkuOrderDetail = new SkuOrderDetail();
            updateSkuOrderDetail.setId(skuOrderDetail.getId());
            updateSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.APPLYING.getCode());
            updateSkuOrderDetail.setApplyRefundTime(new Date());
            updateSkuOrderDetail.setApplyRefundReason(applyRefundReason);
            skuOrderDetailDao.updateById(updateSkuOrderDetail);
        }
    }

    @Override
    public void applyRefundNotify(Integer id, Date successTime, String refundId) throws BusinessException {
        PayOrder payOrder = payOrderDao.findByIdForUpdate(id);
        if ("Y".equals(payOrder.getIsPay())) {
            return;
        }
        Date date = new Date();
        PayOrder param = new PayOrder();
        param.setIsPay("Y");
        param.setPayTime(date);
        param.setBillNo(refundId);
        param.setId(id);
        payOrderDao.updateById(param);
        Integer orderId = Integer.parseInt(payOrder.getOutOrderId().split("-")[1]);
        SkuOrderDetail skuOrderDetail = skuOrderDetailDao.findById(orderId);
        ValidateBusinessException.assertNonNull(skuOrderDetail, ExceptionEnum.ERROR_1801);
        ValidateBusinessException.assertFalse(SkuOrderStatusEnum.SUCCESS.getCode().equals(skuOrderDetail.getApplyRefundStatus()), ExceptionEnum.ERROR_1804);
        SkuOrderDetail updateSkuOrderDetail = new SkuOrderDetail();
        updateSkuOrderDetail.setId(skuOrderDetail.getId());
        updateSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.APPLYSUCCESS.getCode());
        updateSkuOrderDetail.setRefundTime(successTime);
        skuOrderDetailDao.updateById(updateSkuOrderDetail);
        SkuOrderDetailQuery skuOrderDetailQuery = new SkuOrderDetailQuery();
        skuOrderDetailQuery.setSkuOrderId(skuOrderDetail.getSkuOrderId());
        Integer count = skuOrderDetailDao.count(skuOrderDetailQuery);
        logger.info("count===" + count);
        SkuOrder skuOrder = skuOrderDao.findById(skuOrderDetail.getSkuOrderId());
        if (count == 1) {
            logger.info("DELIVER===");
            if (SkuOrderStatusEnum.DELIVER.getCode().equals(skuOrder.getStatus())) {
                SkuOrder updateSkuOrder = new SkuOrder();
                updateSkuOrder.setStatus(SkuOrderStatusEnum.SUCCESS.getCode());
                updateSkuOrder.setId(skuOrderDetail.getSkuOrderId());
                skuOrderDao.updateById(updateSkuOrder);
            } else {
                logger.info("CANCEL===");
                SkuOrder updateSkuOrder = new SkuOrder();
                updateSkuOrder.setStatus(SkuOrderStatusEnum.CANCEL.getCode());
                updateSkuOrder.setId(skuOrderDetail.getSkuOrderId());
                skuOrderDao.updateById(updateSkuOrder);
            }
        }


    }

    @Override
    public void cancelApplyRefund(Integer merchantId, Integer skuOrderDetailId) throws BusinessException {
        SkuOrderDetail skuOrderDetail = skuOrderDetailDao.findByIdAndMerchantId(skuOrderDetailId, merchantId);
        ValidateBusinessException.assertNonNull(skuOrderDetail, ExceptionEnum.ERROR_1801);
        ValidateBusinessException.assertFalse(SkuOrderStatusEnum.SUCCESS.getCode().equals(skuOrderDetail.getApplyRefundStatus()), ExceptionEnum.ERROR_1804);
        SkuOrderDetail updateSkuOrderDetail = new SkuOrderDetail();
        updateSkuOrderDetail.setId(skuOrderDetail.getId());
        updateSkuOrderDetail.setApplyRefundStatus(SkuOrderStatusEnum.CANCEL.getCode());
        skuOrderDetailDao.updateById(updateSkuOrderDetail);
    }


    //通过购物车添加商品
    List<SkuOrderDetail> addSkuOrderByCar(Integer appletType, SkuOrderTypeEnum skuOrderTypeEnum, List<SkuOrderDetail> skuOrderDetails, Integer orderId, Integer merchantId, Double fullReductionPrice, Boolean isHavingPostage, Integer cityId) {
        String isRegion = "N";
        String isPostage = "N";
        String deliveryWay = null;
        List<SkuOrderDetail> skuOrderDetailArrayList = new ArrayList<>();
        Map<Integer, List<SkuOrderDetail>> map = skuOrderDetails.stream().collect(Collectors.groupingBy(SkuOrderDetail::getSupplierId));
        for (Map.Entry<Integer, List<SkuOrderDetail>> entry : map.entrySet()) {
            Integer key = entry.getKey();
            List<SkuOrderDetail> skuOrderDetailList = entry.getValue();
            SkuOrder skuOrder = new SkuOrder();
            skuOrder.setMerchantId(merchantId);
            skuOrder.setOrderId(orderId);
            skuOrder.setTotalPrice(0.0);
            skuOrder.setPayPrice(0.0);
            skuOrder.setIntegralPrice(0.0);
            skuOrder.setType(SkuTypeEnum.SKU.getCode());
            if (SkuOrderTypeEnum.BUY.getCode().equals(skuOrderTypeEnum.getCode())) {
                skuOrder.setStatus(SkuOrderStatusEnum.WAITING.getCode());
            } else {
                skuOrder.setStatus(SkuOrderStatusEnum.PAY.getCode());
            }
            skuOrder.setSupplierId(key);
            skuOrder.setBuyWay(SkuOrderBuyTypeEnum.CAR.getCode());
            skuOrder.setOrderType(skuOrderTypeEnum.getCode());
            skuOrder.setIsPay("N");
            skuOrder.setAppletType(appletType);
            skuOrderDao.insert(skuOrder);
            Double totalPrice = 0.0;
            Double totalPayPrice = 0.0;
            Integer totalIntegral = 0;
            for (SkuOrderDetail skuOrderDetail : skuOrderDetailList) {
                SkuOrderDetail addSkuOrderDetail = new SkuOrderDetail();
                BeanUtilExt.copyProperties(addSkuOrderDetail, skuOrderDetail);
                addSkuOrderDetail.setSkuOrderId(skuOrder.getId());
                skuOrderDetailDao.insert(addSkuOrderDetail);
                if (skuOrderDetail.getDeliveryWay().equals(DeliveryWayEnum.FULLREDUCTION.getCode())) {
                    addSkuOrderDetail.setIsHavingPostage("Y");
                    isPostage = "Y";
                }
                totalPrice += skuOrderDetail.getTotalPrice();
                totalPayPrice += skuOrderDetail.getPayPrice();
                totalIntegral += skuOrderDetail.getTotalInteger();
                skuOrderDetailArrayList.add(addSkuOrderDetail);
                if ("Y".equals(skuOrderDetail.getIsRegion())) {
                    isRegion = "Y";
                }
                deliveryWay = skuOrderDetail.getDeliveryWay();
                if (SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrderTypeEnum.getCode())) {
                    Integer integer = skuSalesInformationDao.deleteStock(skuOrderDetail.getSkuSalesInformationId(), skuOrderDetail.getCount());
                    ValidateBusinessException.assertTrue(integer > 0, ExceptionEnum.ERROR_1826.getCode(), skuOrderDetail.getSkuSalesInformationId() + "," + ExceptionEnum.ERROR_1826.getMessage());
                }
            }
            SkuOrder updateSkuOrder = new SkuOrder();
            updateSkuOrder.setId(skuOrder.getId());
            updateSkuOrder.setTotalPrice(totalPrice);
            updateSkuOrder.setPayPrice(totalPayPrice);
            updateSkuOrder.setIntegralPrice(new BigDecimal(totalPrice + "").subtract(new BigDecimal(totalPayPrice + "")).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
            updateSkuOrder.setIntegral(totalIntegral);
            updateSkuOrder.setIsRegion(isRegion);
            skuOrderDao.updateById(updateSkuOrder);
            if (deliveryWay.equals(DeliveryWayEnum.FULLREDUCTION.getCode())) {
                UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
                urbanFullReductionQuery.setCityId(cityId);
                UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
                if (urbanFullReductionDaoFirst == null) {
                    urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                    urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
                }
                if (isHavingPostage) {
                    SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
                    skuOrderDeliveryDemand.setSkuOrderId(skuOrder.getId());
                    skuOrderDeliveryDemand.setMerchantId(merchantId);
                    skuOrderDeliveryDemand.setPostage(urbanFullReductionDaoFirst.getFreight());
                    skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.WAITING.getCode());
                    skuOrderDeliveryDemand.setCreateTime(new Date());
                    skuOrderDeliveryDemand.setLogistics(deliveryWay);
                    skuOrderDeliveryDemandDao.insert(skuOrderDeliveryDemand);
                } else {
                    SkuOrderDeliveryDemand skuOrderDeliveryDemand = new SkuOrderDeliveryDemand();
                    skuOrderDeliveryDemand.setSkuOrderId(skuOrder.getId());
                    skuOrderDeliveryDemand.setMerchantId(merchantId);
                    skuOrderDeliveryDemand.setPostage(0.0);
                    skuOrderDeliveryDemand.setPostageStatus(SkuOrderStatusEnum.PAY.getCode());
                    skuOrderDeliveryDemand.setPostagePayTime(new Date());
                    skuOrderDeliveryDemand.setCreateTime(new Date());
                    skuOrderDeliveryDemand.setLogistics(deliveryWay);
                    skuOrderDeliveryDemandDao.insert(skuOrderDeliveryDemand);
                }
            }
            skuOrder = skuOrderDao.findById(skuOrder.getId());
            if (skuOrder.getIntegral() > 0 && SkuOrderTypeEnum.ENJOY.getCode().equals(skuOrder.getOrderType())) {
                Merchant before = merchantDao.findById(skuOrder.getMerchantId());
                Integer integer1 = merchantDao.deleteIntegral(skuOrder.getMerchantId(), skuOrder.getIntegral());
                Merchant after = merchantDao.findById(skuOrder.getMerchantId());
                ValidateBusinessException.assertTrue(integer1 > 0, ExceptionEnum.ERROR_1827.getCode(), skuOrder.getId() + "," + ExceptionEnum.ERROR_1827.getMessage());
                MerchantIntegralLog merchantIntegralLog = new MerchantIntegralLog();
                merchantIntegralLog.setMerchantId(skuOrder.getMerchantId());
                merchantIntegralLog.setOperation(IntegralOperationEnum.DEDUCTION.getCode());
                merchantIntegralLog.setBeforeIntegral(before.getIntegral());
                merchantIntegralLog.setAfterIntegral(after.getIntegral());
                merchantIntegralLog.setCreateTime(new Date());
                merchantIntegralLogDao.insert(merchantIntegralLog);
            }
        }
        return skuOrderDetailArrayList;
    }

    @Override
    public Map<Integer, SkuOrderResult> getItemMap() {
        Map<Integer, SkuOrderResult> map = new HashMap<Integer, SkuOrderResult>();
        SkuOrderQuery param = new SkuOrderQuery();
        List<SkuOrder> list = skuOrderDao.page(param, 0, Integer.MAX_VALUE);
        List<SkuOrderResult> resultList = DTOUtils.convertList(list, SkuOrderResult.class);
        for (SkuOrderResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }


}
